【问题标题】:How can I set my UITableView's Header to an Attributed String?如何将 UITableView 的标题设置为属性字符串?
【发布时间】:2015-07-28 22:26:29
【问题描述】:

使用 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
}

但是,一旦 UITableView 中有一个项目,我的 iPad 就会崩溃,而且我从来没有看到标题。

【问题讨论】:

    标签: ios swift


    【解决方案1】:

    您需要在其上创建视图,它不能按原样归因

    表格视图对节标题使用固定字体样式。如果 你想要一个不同的字体样式,返回一个自定义视图(例如,一个 UILabel 对象)在委托方法中 tableView:viewForHeaderInSection: 代替

    信用https://stackoverflow.com/a/11298545/1238867

    【讨论】:

    【解决方案2】:

    如果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 日,星期三”的内容
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-06-28
    • 1970-01-01
    • 2023-04-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多