gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 07:35:03 26 4
gpt4 key购买 nike

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

最佳答案

您看到此行为是因为每个 UIView 都有自己的 SafeAreaLayoutGuide。默认情况下,通用 UIView 子类的 SafeAreaLayoutGuide 不包括您正在寻找的安全区域。您必须使用 TableView 的 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
}

关于swift - 安全区域布局指南不适用于 UITableView 的 BackgroundView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53420760/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com