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

时间:2018-11-21 21:33:15

标签: swift autolayout safearealayoutguide

我遇到的问题是,当标签应该锚定在安全区域布局指南中时,该标签锚定在屏幕的底部边缘。这会将标签带到iPhone行上方。

这是代码...

class CustomTableViewController: UITableViewController {

   override func viewDidLoad() {
       super.viewDidLoad()

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

}

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
   } 

}

enter image description here

2 个答案:

答案 0 :(得分: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
    } 
}

然后在您的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
}

答案 1 :(得分:0)

对于这些年来从 Google 来到这里的任何人来说,为了让它发挥作用,我必须从我的自定义视图中返回 superview 的 safeAreaLayoutGuide。见下文:

...                   

这使所有约束都按预期工作。 确保在添加背景视图之前不要使用 shift

.loc