【发布时间】:2019-01-26 12:52:12
【问题描述】:
我有 UIView() 类,我在其中以编程方式添加标签,并且还给出了约束以根据内容自动调整视图的高度。我已将此类用作 UItableView 部分的 HeaderView。但是这里的问题是这个视图的高度没有根据它的内容进行调整。
这是我的自定义视图代码。
class DynamicHeaderView: UIView {
override func draw(_ rect: CGRect) {
let headerLabel = UILabel()
headerLabel.numberOfLines = 0
headerLabel.sizeToFit()
headerLabel.text = "This is header view. It is dynamicaaly growing text and will automaticaly get adjusted to it"
self.backgroundColor = .green
headerLabel.translatesAutoresizingMaskIntoConstraints = false
self.addSubview(headerLabel)
self.addConstraint(NSLayoutConstraint(item: headerLabel, attribute: .leading, relatedBy: .equal, toItem: self, attribute: .leading, multiplier: 1, constant: 16))
self.addConstraint(NSLayoutConstraint(item: headerLabel, attribute: .trailing, relatedBy: .equal, toItem: self, attribute: .trailing, multiplier: 1, constant: -16))
self.addConstraint(NSLayoutConstraint(item: headerLabel, attribute: .top, relatedBy: .equal, toItem: self, attribute: .top, multiplier: 1, constant: 10))
self.addConstraint(NSLayoutConstraint(item: headerLabel, attribute: .bottom, relatedBy: .equal, toItem: self, attribute: .bottom, multiplier: 1, constant: -10))
} }
我在 viewController 中编写的代码,
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.countriesTable.sectionHeaderHeight = UITableView.automaticDimension;
self.countriesTable.estimatedSectionHeaderHeight = 25 }
func tableView(_ tableView: UITableView,
viewForHeaderInSection section: Int) -> UIView? {
let headerView = DynamicHeaderView()
return headerView
}
高度始终坚持我在 viewDidLoad() 函数中给出的估计标题高度为 25。
【问题讨论】:
-
问题是你没有底部约束。因此自动布局不知道如何自动调整标题视图的大小。下面的答案包括缺少的约束。
-
@DoesData... 错过了从我的代码中添加到此处的那一行但现在我已经更新了。所以我的代码似乎没有问题。
-
您应该删除该行,以便任何来这里的人都能理解这个问题。
-
从这里删除该行没有意义。因为这是我的实际代码。
标签: ios swift uitableview ios-autolayout uitableviewsectionheader