我遇到的问题是,当标签应该锚定在安全区域布局指南中时,该标签锚定在屏幕的底部边缘。这会将标签带到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
}
}
答案 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