iOS(Swift):具有可变高度的TableView节标题-适合内容

由于要求,必须根据“设置”更改动态更改TableView的Header部分的内容。

问题 :随着节标题内容的动态变化,节标题的高度必须改变以适应变化的内容。

解决方案

以下是实现解决方案的步骤

步骤1设置TableView以支持自动调整大小

覆盖func viewDidLoad(){

super.viewDidLoad()

self.tableView.sectionHeaderHeight = UITableViewAutomaticDimension;

self.tableView.estimatedSectionHeaderHeight = 38

}

步骤2区段标题

使用自动布局创建节标题视图,这里我们使用NSLayoutConstraint动态创建自动布局UIView

func tableView(_ tableView:UITableView,viewForHeaderInSection部分:Int)-> UIView? {

让headerView = UIView()

变量约束= [NSLayoutConstraint]()

如果section == 0 {

让flightStatsNoticeLabel = UILabel()

flightStatsNoticeLabel.text =“ Lorem Ipsum只是印刷和排版行业的虚拟文本。 自1500年代以来,Lorem Ipsum一直是业界标准的伪文本,当时一位不知名的打印机拿起一个厨房,然后将其打乱成一本样本书。”

flightStatsNoticeLabel.numberOfLines = 0

flightStatsNoticeLabel.sizeToFit()

让goToSettingsButton = UIButton()

goToSettingsButton.setTitle(“ GoToSettings”,用于:.normal)

goToSettingsButton.setTitleColor(UIColor.black,for:.normal)

goToSettingsButton.layer.borderColor = UIColor.darkGray.cgColor

goToSettingsButton.addTarget(self,action:#selector(someMethod(_ :)),for:.touchUpInside)

//要使用自动版式动态计算视图的大小和位置,我们必须将属性translationsAutoresizingMaskIntoConstraints设置为false

flightStatsNoticeLabel.translatesAutoresizingMaskIntoConstraints = false

goToSettingsButton.translatesAutoresizingMaskIntoConstraints = false

headerView.addSubview(flightStatsNoticeLabel)

headerView.addSubview(goToSettingsButton)

//向标题视图添加自动布局约束

Constraints.append(NSLayoutConstraint(item:flightStatsNoticeLabel,attribute:.lead,relatedBy:.equal,toItem:headerView,attribute:.lead,乘数:1.0,常数:16.0))

Constraints.append(NSLayoutConstraint(item:flightStatsNoticeLabel,attribute:.trailing,relatedBy:.equal,toItem:headerView,attribute:.trailing,multiplier:1.0,constant:-16.0))

Constraints.append(NSLayoutConstraint(item:flightStatsNoticeLabel,attribute:.top,relatedBy:.equal,toItem:headerView,attribute:.top,乘数:1.0,常数:10.0))

Constraints.append(NSLayoutConstraint(item:goToSettingsButton,attribute:。Lead,relatedBy:.equal,toItem:headerView,attribute:。Lead,乘数:1.0,常数:16.0))

prefix.append(NSLayoutConstraint(item:goToSettingsButton,属性:.top,relatedBy:.equal,toItem:flightStatsNoticeLabel,属性:.bottom,乘数:1.0,常数:10.0))

Constraints.append(NSLayoutConstraint(item:goToSettingsButton,attribute:.height,relatedBy:.equal,toItem:nil,attribute:.notAnAttribute,乘数:1.0,常数:38))

Constraints.append(NSLayoutConstraint(item:goToSettingsButton,attribute:.width,relatedBy:.equal,toItem:nil,attribute:.notAnAttribute,乘数:1.0,常数:200))

Constraints.append(NSLayoutConstraint(item:goToSettingsButton,属性:.bottom,relatedBy:.equal,toItem:headerView,属性:.bottom,乘数:1.0,常数:-10.0))

headerView.addConstraints(constraints)

返回headerView

}

返回headerView

}

步骤3 :省略heightForHeaderInSection方法:

删除heightForHeaderInSection方法

样品

因此,我们实现了具有可变高度的TableView节标题-以适合内容。