Autolayout constraints push content outside of the view

问题描述 投票:0回答:0

我在 tableHeaderView 中显示标签时遇到问题。文本被推出视图到顶部。检查 tableHeaderView 动态高度设置后,看来我一定是把约束弄乱了。你能告诉我为什么我的 tableHeaderView 没有调整到其中标签的大小吗?这是代码:

override func viewDidLoad() {
    super.viewDidLoad()
    secondTableView.delegate = self
    secondTableView.dataSource = self
    
    let tableHeader = UIView()
    secondTableView.tableHeaderView = tableHeader
    
    let size = tableHeader.systemLayoutSizeFitting(UIView.layoutFittingCompressedSize)
    let height = size.height
    let width = size.width
    tableHeader.frame = CGRectMake(0, 0, width, height)
    
    tableHeader.translatesAutoresizingMaskIntoConstraints = true
    
    tableHeader.backgroundColor = .systemOrange
    
    let labelOne = UILabel(frame: tableHeader.bounds)
    labelOne.text = "USER:"
    tableHeader.addSubview(labelOne)
    
    labelOne.translatesAutoresizingMaskIntoConstraints = false
    labelOne.centerXAnchor.constraint(equalTo: tableHeader.centerXAnchor).isActive = true
    
    let labelTwo = UILabel(frame: tableHeader.bounds)
    labelTwo.text = "Inherited text here: \(insertionText)"
    tableHeader.addSubview(labelTwo)
    
    labelTwo.numberOfLines = 0
    labelTwo.textAlignment = .center
    
    labelTwo.translatesAutoresizingMaskIntoConstraints = false
    labelTwo.topAnchor.constraint(equalTo: labelOne.bottomAnchor, constant: 0).isActive = true
    labelTwo.leadingAnchor.constraint(equalTo: tableHeader.layoutMarginsGuide.leadingAnchor, constant: 0).isActive = true
    labelTwo.trailingAnchor.constraint(equalTo: tableHeader.layoutMarginsGuide.trailingAnchor, constant: 0).isActive = true
    labelTwo.bottomAnchor.constraint(equalTo: tableHeader.bottomAnchor, constant: 11).isActive = true

}
ios swift autolayout constraints tableview
© www.soinside.com 2019 - 2024. All rights reserved.