簡體   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