我确实认为使用自定义 UILabel 是一种更好的方法,因为您可以控制所有属性。
首先,一个方便的函数来计算 UILabel 的高度。 (以下是我的特定项目的版本)。请注意,我设置了NSMutableParagraphStyle,我认为这是处理换行符、行距等的最佳方式。
internal func heightForLabel(attributedString:NSMutableAttributedString, font:UIFont, width:CGFloat, lineSpacing: CGFloat) -> CGFloat{
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineSpacing = lineSpacing
let label:UILabel = UILabel(frame: CGRect(x:0, y:0, width:width, height:CGFloat.greatestFiniteMagnitude))
label.numberOfLines = 0
label.lineBreakMode = .byWordWrapping
label.font = font
label.textAlignment = .left
attributedString.addAttribute(NSParagraphStyleAttributeName, value:paragraphStyle, range:NSMakeRange(0, attributedString.length))
label.attributedText = attributedString
label.sizeToFit()
return label.frame.height
}
然后在您的视图控制器中,预先计算节标题高度
fileprivate let sectionHeaders = ["Header1", "Loooooooooooooooooooooong Header which occupies two lines"]
fileprivate var sectionHeaderHeights : [CGFloat] = []
override func viewDidLoad() {
super.viewDidLoad()
//Calculate the label height for each section headers, then plus top and down paddings if there is any. Store the value to `sectionHeaderHeights`
}
UITableViewDelegate 方法
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return sectionHeaderHeights[section]
}
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let sectionHeader = UIView(frame: CGRect(x: 0, y: 0, width: view.frame.width, height: sectionHeaderHeights[section]-paddings))
sectionHeader.backgroundColor = .clear
let sectionTitleLabel = UILabel()
sectionTitleLabel.text = sectionTitles[section]
sectionTitleLabel.font = UIFont(name: "GothamPro", size: 18)
sectionTitleLabel.textColor = .black
sectionTitleLabel.backgroundColor = .clear
sectionTitleLabel.frame = CGRect(x: padding, y: sectionHeader.frame.midY, width: sectionTitleLabel.frame.width, height: sectionTitleLabel.frame.height)
sectionHeader.addSubview(sectionTitleLabel)
return sectionHeader
}