我试图在表格 View 的顶部画一条线,如下所示:
func addTopLineToTableView() {
let layer = CALayer()
layer.backgroundColor = UIColor.green.cgColor
layer.frame = CGRect(x: tableView.frame.origin.x, y: tableView.frame.origin.y, width: tableView.frame.size.width, height: 1.0)
view.layer.addSublayer(layer)
}
这在除 iPhone X 之外的所有设备上都能完美运行。
我尝试获取 safeAreaInsets
和 safeAreaLayoutGuide
但似乎没有任何作用。
非常感谢任何帮助!
编辑
以上是最终结果应该是什么样子。这里的 TableView 有红色背景,我的绿色 CALayer 正如预期的那样位于顶部。它已使用上面的函数放置在那里。这是它在除 iPhone X 之外的所有设备上的外观。
以下是在 iPhone X 上运行相同代码时会发生的情况。
最佳答案
就像之前 friend 说的,线条可以设置到零件上,可以扩展 View
extension UIView {
@IBInspectable var topBorderWidth: CGFloat {
get {
return 0.0 // Just to satisfy property
}
set {
let line = UIView(frame: CGRect(x: 0.0, y: 0.0, width: bounds.width, height: newValue))
line.translatesAutoresizingMaskIntoConstraints = false
line.backgroundColor = UIColor.green
self.addSubview(line)
let views = ["line": line]
let metrics = ["lineWidth": newValue]
addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "|[line]|", options: [], metrics: nil, views: views))
addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|[line(==lineWidth)]", options: [], metrics: metrics, views: views))
}
}
}
这样的使用
testView.topBorderWidth = 1
关于ios - iPhone x 上的 Y 位置关闭,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48158852/