关于3x手机渲染问题

夏风已过 / 2023-08-13 / 原文

iOS 中利用通过 setFrame 来固定一个 view 的位置,例如下面代码:

let dView = UIView()
dView.frame = CGRect(x: 100, y: 100, width: 100, height: 70.8)
dView.backgroundColor = .orange
view.addSubview(dView)

通过 Xcode 的 Debug View Hierarchy 看到,dView 的 frame 也确实是我们设置的。但是如果使用 Autolayout 呢?

let dView = UIView()
dView.backgroundColor = .orange
view.addSubview(dView)
dView.translatesAutoresizingMaskIntoConstraints = false

dView.topAnchor.constraint(equalTo: view.topAnchor, constant: 100).isActive = true
dView.leftAnchor.constraint(equalTo: view.leftAnchor, constant: 100).isActive = true
dView.widthAnchor.constraint(equalToConstant: 73.8).isActive = true
dView.heightAnchor.constraint(equalToConstant: 100).isActive = true

我们再次通过 Debug View Hierarchy 可以看到,dView的 frame 为(100, 100, 73.667, 100)。

在3x手机中,autolayout 渲染的只有0,0.333,0.667,1。这样也就不难理解设置分割线都是 1 / UIScreen.main.scale 。

除了 autolayout 中有这个问题,在 UIScrollView 的 scrollViewDidscroll 回调中,也有该问题。所以可能会出现滑动的问题。(比如:UIScrollView嵌滚动时,上UIScrollView滚动高度设置为73.8,但是系统返回的是73.667,这样下UIScrollView永远无法滚动)