4

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.

David Skrundz
  • 13,067
  • 6
  • 42
  • 66
Jonathan Allen Grant
  • 3,408
  • 6
  • 30
  • 53

2 Answers2

4

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

Community
  • 1
  • 1
JSA986
  • 5,870
  • 9
  • 45
  • 91
  • Actually you can change some attribute, like this: http://stackoverflow.com/questions/19802336/ios-7-changing-font-size-for-uitableview-section-headers – NSDeveloper Jul 29 '15 at 03:15
1

If textArr just has one element, this piece of code will crash the app.

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))

Just make sure headerString has at least two ", ", then you can use textArr[2]. If the text can't meet the conditions, you should use if to avoid a crash.

shim
  • 9,289
  • 12
  • 69
  • 108
NSDeveloper
  • 1,630
  • 15
  • 25