繁体   English   中英

使用NSMutableAttributedStrings快速更改文本颜色

[英]Swift change color of text using NSMutableAttributedStrings

我有一个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

这一切的输出是 在此输入图像描述

其中数字34对应于object.valueForKey("example1")!.description ,所以问题是数字不是红色,而第二部分( object.valueForKey("example2")!.description )被替换为{

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

我认为问题可能在于分配给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

不确定你是否希望字符串的第二部分是红色或其他颜色,所以我把它变黑了。

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

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

这是属性文本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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM