【问题标题】:Resize a UITableView Header without autolayout在没有自动布局的情况下调整 UITableView 标题的大小
【发布时间】:2017-08-07 09:46:44
【问题描述】:

是否可以在设置文本后调整UITabeView Header 的大小? 在我的 xib 中,我得到了一个 TableView,其标题为 1 行文本的高度为 42。对于 2 行,我需要 52 的高度,对于 3,我需要 62。标题动态设置为标题。但是 heightForHeaderInSection 函数在生命周期设置标题文本之前被调用。所以可能没有显示第 2 行和第 3 行。

我写了一个方法告诉我标题有多少行文本但是如何更新标题?如果我打电话给tableView.reloadData(),我最终会陷入无限循环。如果我为每个 lineamoun 设置 var t 我发现heightForheaderInSection 从未被调用过。

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

    let cell = tableView.dequeueReusableCell(withIdentifier: headerCell) as! SectionHeader
    cell.titleLabel.text = self.sectionTitle

    linesOfHeader = cell.getNumberOfLines()


    return cell
  }



 func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        if(linesOfHeader == 1) { return 44}
        else if(linesOfHeader == 2) {return 52}
        else { return 62}
  }

【问题讨论】:

  • linesOfHeader 设置一个属性观察器,并从linesOfHeaderdisSet 方法内部调用tableView.reloadData()。这样,每次linesOfHeader 更改时,您的tableView 只会重绘一次。
  • 字符串的boundedrect方法可以帮助您获取标签的高度和宽度,您可以从中将高度传递给标题。
  • @DávidPásztor 相同的循环。 reloadData() 调用 viewForHeaderInSection 我设置页眉的行。所以我最终会陷入一个循环。
  • 所以不要在viewForHeaderInsection中设置linesOfHeader,而是在行数实际可以改变的时候设置。
  • 此时。当我设置文本时,行会发生变化。所以我必须把它放在那里。

标签: ios swift uitableview swift3 header


【解决方案1】:

支持动态标题高度的更好解决方案是使用“UITableViewAutomaticDimension”,如下所示:

在 viewDidLoad 添加这些行:

self.tableView.sectionHeaderHeight = UITableViewAutomaticDimension
self.tableView.estimatedSectionHeaderHeight = 50

并删除函数 heightForHeaderInSection

然后让标签扩展到需要的行数

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

    let cell = tableView.dequeueReusableCell(withIdentifier: headerCell) as! SectionHeader
       cell.titleLabel.text = self.sectionTitle
       cell.titleLabel.numberOfLines = 3
     return cell
    }

如果标题高度与单元格高度重叠,则将这两行添加到 viewDidLoad

    self.tableView.rowHeight = UITableViewAutomaticDimension
    self.tableView.estimatedRowHeight = 40 // estimated cell height

【讨论】:

  • numberOfLines 参数应该设置为 0,所以Autolayout 可以自己算出必要的行数。另外,请记住,UITableViewAutomaticDimension 工作需要使用Autolayout
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-02-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-05-03
相关资源
最近更新 更多