使用NSMutableAttributedStrings快速更改文本颜色

时间:2014-09-17 13:49:23

标签: ios swift uitableview nsattributedstring textcolor

我有一个UITableView,我希望在同一行中使用不同的颜色显示每一行的文字。

我已经尝试过这段代码,尝试从Obj-C翻译,但我不能让它工作

        let object = self.fetchedResultsController.objectAtIndexPath(indexPath) as NSManagedObject

        var attrString: NSMutableAttributedString = NSMutableAttributedString(string: object.valueForKey("example1")!.description)
        attrString.addAttribute(NSForegroundColorAttributeName, value: UIColor.redColor(), range: NSMakeRange(0, attrString.length))

        var stringToCell:String = String(format: "%@    %@", attrString, object.valueForKey("example2")!.description)
        cell.textLabel?.text = stringToCell

这一切的输出是 enter image description here

其中数字34对应object.valueForKey("example1")!.description,因此问题是数字红色,第二部分(object.valueForKey("example2")!.description)被{{1 }}

如果我留下关于{的这段代码,行文本会正确显示。

3 个答案:

答案 0 :(得分:11)

我认为问题可能在于分配给cell.textLabel?.text而不是cell.textLabel?.attributedText。也许是这样的:

let object = self.fetchedResultsController.objectAtIndexPath(indexPath) as NSManagedObject

var attrString: NSMutableAttributedString = NSMutableAttributedString(string: object.valueForKey("example1")!.description)
attrString.addAttribute(NSForegroundColorAttributeName, value: UIColor.redColor(), range: NSMakeRange(0, attrString.length))

var descString: NSMutableAttributedString = NSMutableAttributedString(string:  String(format: "    %@", object.valueForKey("example2")!.description))
descString.addAttribute(NSForegroundColorAttributeName, value: UIColor.blackColor(), range: NSMakeRange(0, descString.length))

attrString.appendAttributedString(descString);
cell.textLabel?.attributedText = attrString

不确定您是否希望字符串的第二部分为红色或其他颜色,因此我将其设为黑色。

答案 1 :(得分:1)

如果可以,请避免使用NSMutableAttributedString,只需使用构造函数传递属性:

private func PullToRefreshAttributedStringWithColor(color:UIColor) -> NSAttributedString {
  return NSAttributedString(string: "Pull to Refresh", attributes: [
      NSForegroundColorAttributeName:color
    ])
}

答案 2 :(得分:0)

以下是属性文字Swift 3

的示例
let mainText = "Here is a example of attributedString"
let attributeText = "attributedString"
let range = (mainText as NSString).range(of: attributeText)
let attributedString = NSMutableAttributedString(string:mainText)

attributedString.addAttribute(NSAttributedStringKey.foregroundColor, value: UIColor.red, range: range)
attribute.addAttribute(NSFontAttributeName, value: UIFont.systemFont(ofSize: 14) , range: range)

lblTitle.attributedText = attributedString