ios - heightForHeaderInSection 只调用一次

标签 ios uitableview layout header swift3

在 Swift 3 中编码。拥有一个带有自定义单元格和标题的 tableView。

我有一个带有自定义单元格和标题的 tableView。 header 中有两 (2) 个标签,并且具有动态单元格高度,因为标签可能很长。我的问题是第一次配置 tableView 和部分时,标签按应有的方式显示,但是,在向下滚动然后备份后,标题的布局以某种方式中断。

When tableView first loads and user scrolls down everything appears fine

正如您在下面看到的,在我向下滚动然后向上滚动到单元格后,标签被截断了。

After scrolling down and back up label is cut off

打印出正在调用的方法后,我发现第一次向下滚动 tableView 时调用了以下两 (2) 个覆盖函数。

override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
    print("\(section) heightForHeaderInSection")
    print("\(section) returning AUTO for header")
    return UITableViewAutomaticDimension
}

override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
    print("\(section) viewForHeaderInSection")
    let header = tableView.dequeueReusableCell(withIdentifier: "QuestionHeader") as! QuestionHeader
    header.delegate = self
    header.contentView.backgroundColor = UIColor.groupTableViewBackground
    header.questionTextLabel.text = String(questionStringArray[section])
    header.questionNumberLabel.text = (String(section + 1) + ")")
    return header.contentView
}

但是当我向上滚动时,仅调用 viewForHeader 函数,我认为因为不再将高度设置为 UITableViewAutomaticDimension,所以标签会被截断?

有什么想法吗?

最佳答案

您应该从 tableView: viewForHeaderInSection: 方法返回 header 而不是 header.contentView:

override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
  let header = tableView.dequeueReusableCell(...
  ...
  return header
}

关于ios - heightForHeaderInSection 只调用一次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39903830/

相关文章:

ios - 在 Apple Watch 上登录 Parse.com

ios - 创建一个通过 Swift 3 (iOS) 中的套接字接收数据的 InputStream

ios - 如何在新行将 JSON 数组数据打印到 Swift3 中的 UILabel

.net - 与字体相关的控制定位

java - BoxLayout 忽略 setYAlighment

ios - 我应该如何在 Swift 中创建一个依赖于另一个变量的变量?

ios - SwiftUI @State 更改正在显示的图像

cocoa-touch - 如何 : hide keyboard when UITextView is out of view?

ios - 如何从核心数据(实体)中删除行 ios swift

asp.net-mvc-3 - 类型 'System.Web.IHtmlString' 在未引用的程序集中定义