ios - iPhone x 上的 Y 位置关闭

标签 ios swift iphone-x

我试图在表格 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 之外的所有设备上都能完美运行。

我尝试获取 safeAreaInsetssafeAreaLayoutGuide 但似乎没有任何作用。

非常感谢任何帮助!

编辑

Table border working

以上是最终结果应该是什么样子。这里的 TableView 有红色背景,我的绿色 CALayer 正如预期的那样位于顶部。它已使用上面的函数放置在那里。这是它在除 iPhone X 之外的所有设备上的外观。

Table border not working

以下是在 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/

相关文章:

ios - XCODE 中的 Json.Net 错误 - System.Reflection.Emit

swift - 为什么我使用 NSManagedObject 会得到一个基于 block 的崩溃清除 KVO?

swift - iOS 网络扩展错误创建 TUN/TAP 接口(interface) SIOCGIFMTU 失败 : device not configured

ios - 获取 iPhone X (10) ios 11 的屏幕尺寸(每条扫描线)(以像素为单位)

ios - iPhone X 在 View Controller 上隐藏主页指示器

ios - 试图在 swift 中检测 iphone x 总是返回 false

ios - 获取html中特定标签之间的数据

ios - 当您将 self 分配给委托(delegate)时,究竟会发生什么?

iphone - Objective-C 返回一个数组 - 内存问题

ios - Swift URLSession 在制​​作 PageView 之前无法正常工作