如何在多行中显示包含长文本的tableview节标题?

时间:2016-10-23 16:35:44

标签: ios swift uitableview

我正在使用具有多个部分的表视图控制器,其中一些部分具有长文本。当我使用titleForHeaderSection时,如果文本的长度超过tableview框架,则文本会被截断。我想在下一行显示文本。

2 个答案:

答案 0 :(得分:1)

您可以使用viewForHeaderInSection创建headerView。将UILabel作为子视图添加到headerView。使用UILabel的多行属性以多行显示文本。同时设置headerView的高度。

答案 1 :(得分:1)

请尝试使用titleForHeaderInSection,而不要使用viewForHeaderInSection。此方法要求您返回视图,但由于UILabelUIView的子类,您还可以返回标签!

func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
    let label = UILabel()
    label.backgroundColor = UIColor.black
    label.textColor = UIColor.white
    label.lineBreakMode = .byWordWrapping
    label.numberOfLines = 0
    label.text = "Here's to the crazy ones. The misfits. The rebels. The troublemakers. The round pegs in the square holes. The ones who see things differently. They're not fond of rules. And they have no respect for the status quo. You can quote them, disagree with them, glorify or vilify them. About the only thing you can't do is ignore them. Because they change things. They push the human race forward. And while some may see them as the crazy ones, we see genius. Because the people who are crazy enough to think they can change the world, are the ones who do."
    return label
}

您会注意到,使用此方法,文本会一直显示在表格视图的左右边缘。在大多数情况下,这看起来并不是很好,特别是如果您的表视图占用了设备的整个宽度。

一个简单的解决方法:创建UILabel的自定义子类(我将调用我的TableViewHeaderLabel)。在这个子类中,我们将向标签添加插入内容。我们还可以将自动换行,背景颜色等移动到此标签中,以使我们的ViewController文件更清晰!

这就是TableViewHeaderLabel.swift的样子:

import UIKit

class TableViewHeaderLabel: UILabel {

    var topInset:       CGFloat = 0
    var rightInset:     CGFloat = 12
    var bottomInset:    CGFloat = 0
    var leftInset:      CGFloat = 12

    override func drawText(in rect: CGRect) {

        let insets: UIEdgeInsets = UIEdgeInsets(top: self.topInset, left: self.leftInset, bottom: self.bottomInset, right: self.rightInset)
        self.setNeedsLayout()

        self.textColor = UIColor.white
        self.backgroundColor = UIColor.black

        self.lineBreakMode = .byWordWrapping
        self.numberOfLines = 0

        return super.drawText(in: UIEdgeInsetsInsetRect(rect, insets))
    }

}

然后使用它看起来像这样:

func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
    let label = TableViewHeaderLabel()
    label.text = "Here's to the crazy ones. The misfits. The rebels. The troublemakers. The round pegs in the square holes. The ones who see things differently. They're not fond of rules. And they have no respect for the status quo. You can quote them, disagree with them, glorify or vilify them. About the only thing you can't do is ignore them. Because they change things. They push the human race forward. And while some may see them as the crazy ones, we see genius. Because the people who are crazy enough to think they can change the world, are the ones who do."
    return label
}