如何将UITableView的表头设置为富文本字符串?

4
使用Swift,我该如何将UITableViewHeader中的文本设置为富文本字符串?
我尝试过以下方式:
func tableView(tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
    // Text Color/Font
    let header = view as! UITableViewHeaderFooterView
    let headerString = header.textLabel?.text!
    let textArr = headerString!.componentsSeparatedByString(", ")
    let attributesBold = [
        NSFontAttributeName : UIFont.boldSystemFontOfSize(20), NSForegroundColorAttributeName : UIColor(red: 44.0/255.0, green: 50.0/255.0, blue: 75.0/255.0, alpha: 1.0)]
    let attributesNorm = [
        NSFontAttributeName : UIFont.systemFontOfSize(20), NSForegroundColorAttributeName : UIColor(red: 44.0/255.0, green: 50.0/255.0, blue: 75.0/255.0, alpha: 1.0)]
    var fullText = NSMutableAttributedString(string: headerString!)
    let count = textArr[0].characters.count + 2 + textArr[1].characters.count + 2 //total length of bold string
    fullText.addAttributes(attributesBold, range: NSRange(location: 0, length: count))
    fullText.addAttributes(attributesNorm, range: NSRange(location:count, length: textArr[2].characters.count))
    header.textLabel?.attributedText = fullText
}

但是我的iPad在UITableView中只添加一个项目时就崩溃了,我从没有看到过标题。

2个回答

4

您需要在其上创建视图,不能直接使用。

表视图为部分标题使用固定字体样式。如果您想要不同的字体样式,请在委托方法tableView:viewForHeaderInSection:中返回自定义视图(例如UILabel对象)

来源:https://stackoverflow.com/a/11298545/1238867


实际上,您可以更改一些属性,例如:https://dev59.com/jWIj5IYBdhLWcg3w4Ivt - NSDeveloper

1
如果textArr只有一个元素,这段代码会导致应用程序崩溃。
let count = textArr[0].characters.count + 2 + textArr[1].characters.count + 2 //total length of bold string
fullText.addAttributes(attributesBold, range: NSRange(location: 0, length: count))
fullText.addAttributes(attributesNorm, range: NSRange(location:count, length: textArr[2].characters.count))

只需确保headerString至少有两个", ",然后您就可以使用textArr[2]。 如果文本无法满足条件,则应使用if来避免崩溃。


它确实有。每个标题都会有类似于“2015年7月29日,星期三”的日期。 - Jonathan Allen Grant

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接