安全区域布局指南不适用于 UITableView 的 BackgroundView

dam*_*sar 5 autolayout swift safearealayoutguide

我遇到的问题是,当标签应该锚定到安全区域布局指南时,标签却锚定到屏幕的底部边缘。这将使标签位于 iPhone 系列之上。

这是代码...

class CustomTableViewController: UITableViewController {

   override func viewDidLoad() {
       super.viewDidLoad()

       tableView.tableFooterView = UIView(frame: .zero)
       tableView.backgroundView = CustomBackgroundView()
   } 

}
Run Code Online (Sandbox Code Playgroud)

class CustomBackgroundView: UIView {

   override init(frame: CGRect) {
       super.init(frame: frame)
       setupSubviews()
   }

   required init?(coder aDecoder: NSCoder) {
       fatalError("init(coder:) has not been implemented")
   }

   private func setupSubviews() {
       let label = UILabel()
       label.text = "Hello, World!"
       label.textAlignment = .center
       label.translatesAutoresizingMaskIntoConstraints = false

       addSubview(label)

       label.centerXAnchor.constraint(equalTo: centerXAnchor).isActive = true
       label.bottomAnchor.constraint(equalTo: safeAreaLayoutGuide.bottomAnchor).isActive = true
   } 

}
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

joe*_*ern 0

您看到这种行为是因为每个人UIView都有自己的SafeAreaLayoutGuide. 默认情况下,SafeAreaLayoutGuide通用子UIView类不包括您正在查找的安全区域。您必须使用表视图的 SafeAreaLayoutGuide。

你可以这样做:

class CustomBackgroundView: UIView {

    var safetyAreaBottomAnchor: NSLayoutYAxisAnchor? {
        didSet {
            guard let safetyAreaBottomAnchor = safetyAreaBottomAnchor else { return }
            label.bottomAnchor.constraint(equalTo: safetyAreaBottomAnchor).isActive = true
        }
    }

    private let label = UILabel()

    override init(frame: CGRect) {
        super.init(frame: frame)
        setupSubviews()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    private func setupSubviews() {
        label.text = "Hello, World!"
        label.textAlignment = .center
        label.translatesAutoresizingMaskIntoConstraints = false

        addSubview(label)

        label.centerXAnchor.constraint(equalTo: centerXAnchor).isActive = true
    } 
}
Run Code Online (Sandbox Code Playgroud)

然后在你的 UITableViewController 中执行以下操作:

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
    let customBackgroundView = CustomBackgroundView()
    tableView.tableFooterView = UIView(frame: .zero)
    tableView.backgroundView = customBackgroundView

    customBackgroundView.safetyAreaBottomAnchor = tableView.safeAreaLayoutGuide.bottomAnchor
}
Run Code Online (Sandbox Code Playgroud)