titleForHeaderInSection的文本太长

时间:2016-07-08 17:26:13

标签: ios swift uitableview

所以我的问题是我的文字上面的文字太长而且被切断了。

example

任何方法可以解决这个问题,比如让它长两行吗?

感谢任何帮助

3 个答案:

答案 0 :(得分:3)

您需要定义heightForHeaderInSection并自定义viewForHeaderInSection。您可以将所有标题高度修复为足以容纳所有行的值,也可以计算特定标题所需的高度(如下所示)。

let headerFont:UIFont = UIFont.systemFontOfSize(14);
let headerTexts = ["one line", "two line test123 sadfjklsadf asdjfklasjdflk asdfjklasdjfl asdfjklsadf"];

override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
    return 2;
}

override func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
    return heightOfHeaderText(headerTexts[section]);
}

func heightOfHeaderText(text:String) -> CGFloat{
    return NSString(string: text).boundingRectWithSize(
        CGSizeMake(self.tableView.frame.size.width, 999),
        options: NSStringDrawingOptions.UsesLineFragmentOrigin,
        attributes: [NSFontAttributeName : headerFont],
        context: nil).size.height;


}

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

    let headerLabel:UILabel = UILabel.init(frame: CGRectMake(0, 0, tableView.frame.size.width, self.tableView(tableView, heightForHeaderInSection: section)));
    headerLabel.numberOfLines = 0;
    headerLabel.lineBreakMode = NSLineBreakMode.ByWordWrapping;
    headerLabel.font = headerFont;
    headerLabel.text = headerTexts[section];

    return headerLabel;


}

答案 1 :(得分:1)

制作带有标签的自定义视图。并使用viewForHeaderInSection委托方法将文本分配给该标签并返回此视图。

编辑:

查看此链接 Customize UITableView header section

答案 2 :(得分:0)

有一种直接的方法可以避免额外的计算,在将您的UITableView创建为分组-

后,重写UITableViewDelegate的3种方法
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
    return headerTexts[section]
}

func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
    return UITableViewAutomaticDimension
}


func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
    if let headerLabel = view as? UITableViewHeaderFooterView {
        headerLabel.numberOfLines = 0
        headerLabel.lineBreakMode = NSLineBreakMode.ByWordWrapping
        headerLabel.font = headerFont
        headerLabel.text = headerTexts[section]
    }
}
相关问题