How can I set my UITableView's Header to an Attributed String?

时间:2015-07-28 22:26:30

标签: ios swift

Using Swift, how can I set the text in the UITableViewHeader to an attributed String?

I've tried this:

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
}

But my iPad crashes as soon as one item is in the UITableView, and I never see the header.

2 个答案:

答案 0 :(得分:2)

You will need to create view on top of it, it cannot be attributed as is

The table view uses a fixed font style for section header titles. If you want a different font style, return a custom view (for example, a UILabel object) in the delegate method tableView:viewForHeaderInSection: instead

credit https://stackoverflow.com/a/11298545/1238867

答案 1 :(得分: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以避免崩溃。

相关问题