自定义UITableViewHeaderFooterView的标签被切断

时间:2018-03-13 23:20:09

标签: ios swift uitableview

我有一个带有自定义部分页脚的tableView。每个页脚都有一个标签,可以显示多行文本。在某些标签中,我的文字会被截断,我想知道如何避免这种情况。这是一个例子:

enter image description here

如您所见,三个标签中的两个被切断。我希望标签随文本一起扩展(就像中间的标签一样)。

这是一个展示问题github

的项目

我的自定义页脚类:

class CustomFooter: UITableViewHeaderFooterView {

public static var nib: UINib {
    return UINib(nibName: "CustomFooter", bundle: nil)
}

@IBOutlet weak var label: UILabel!

public func heightWithExpectedWidth(_ width: CGFloat) -> CGFloat {
    label.preferredMaxLayoutWidth = width;
    return systemLayoutSizeFitting(UILayoutFittingCompressedSize).height
}

}

来自我的视图控制器类的相关方法:

private let cellReuseIdentifier = "CellReuseIdentifier"
private let footerReuseIdentifier = "FooterReuseIdentifier"

override func viewDidLoad() {
    super.viewDidLoad()
    tableView.register(UITableViewCell.self, forCellReuseIdentifier: cellReuseIdentifier)
    tableView.register(CustomFooter.nib, forHeaderFooterViewReuseIdentifier: footerReuseIdentifier)
}

func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
    guard let footer = tableView.dequeueReusableHeaderFooterView(withIdentifier: footerReuseIdentifier) as? CustomFooter else {
        return nil
    }
    footer.label.text = sections[section].footerText
    return footer
}

func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
    guard let footer = self.tableView(tableView, viewForFooterInSection: section) as? CustomFooter else {
        return 0
    }
    return footer.heightWithExpectedWidth(tableView.bounds.width)
}

我尝试过使用约束和heightFor方法,但没有运气。我不明白问题的根源,我们非常感谢任何帮助或指示。

项目演示问题github

1 个答案:

答案 0 :(得分:2)

1)从public func heightWithExpectedWidth(_ width: CGFloat) -> CGFloat

中删除CustomFooter.swift

2)将以下代码添加到视图控制器的viewDidLoad方法

tableView.sectionFooterHeight = UITableViewAutomaticDimension
tableView.estimatedSectionFooterHeight = 44

3)更新您的heightForFooterInSection方法,如下所示:

func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
  guard let _ = self.tableView(tableView, viewForFooterInSection: section) as? CustomFooter else {
     return 0
  }
  return UITableViewAutomaticDimension
}

现在,它应该有效。

<强>更新

要支持方向更改,请添加以下代码:

override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
  super.viewWillTransition(to: size, with: coordinator)
  tableView.reloadData()
}
相关问题