2017-01-20 23 views
-2

我有一個表格視圖,裏面有單個標籤的單元格,沒有什麼奇怪的。 我想這一個標籤包含了2種不同顏色的文字:UITableViewCell - 具有歸屬文本的UILabel

let red = NSAttributedString(string: "Red color", 
         attributes: 
           [NSForegroundColorAttributeName: UIColor.redColor(), 
              NSFontAttributeName: normalFont]) 
let blue = NSAttributedString(string: "Blue color", 
          attributes: 
           [NSForegroundColorAttributeName: UIColor.blueColor(), 
              NSFontAttributeName: boldFont]) 

let attributedText = NSMutableAttributedString(attributedString: red) 
attributedText.appendAttributedString(blue) 

self.labelInformation.attributedText = attributedText 

問題:文字全爲藍色,我不明白爲什麼。

如果我打印出來attributedText我得到:

Red color 
{ 
    NSColor = "UIExtendedSRGBColorSpace 1 0 0 1"; 
    NSFont = "<UICTFont: 0x104249d80> font-family: \"Open Sans\"; font-weight: normal; font-style: normal; font-size: 18.00pt"; 
}Blue color{ 
    NSColor = "UIExtendedSRGBColorSpace 0 0 1 1"; 
    NSFont = "<UICTFont: 0x10b51d7c0> font-family: \"Open Sans\"; font-weight: bold; font-style: normal; font-size: 20.00pt"; 
} 

這似乎ok了!

問題必須與表視圖相關,因爲在視圖上應用相同的代碼。

有什麼建議嗎?

更新

此代碼是一個自定義單元格圖的方法中:

class CustomViewCell: UITableViewCell { 

    func setup() { 
     // code above 
    } 

} 

在控制器:

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { 
    let cell = tableView.dequeueReusableCellWithIdentifier("CustomIdentifier") as! CustomTableViewCell 
    cell.setup() 
    return cell 
} 
+1

當我在寫這個代碼的等效代碼迅速3.0其工作相當好。 –

+0

也一樣。在工作場所swift 3. – vikingosegundo

+0

此外,是否有任何代碼相關的'self.labelInformation'這個片段後發佈 –

回答

-1

嘗試類似的東西

myMutableString.addAttribute(NSFontAttributeName, 
    //: Make a big blue P 
     myMutableString.addAttribute(
      NSFontAttributeName, 
      value: UIFont(
       name: "AmericanTypewriter-Bold", 
       size: 36.0)!, 
      range: NSRange(
       location:0, 
       length:1)) 
     myMutableString.addAttribute(
      NSForegroundColorAttributeName, 
      value: UIColor.blue(), 
      range: NSRange(
       location:0, 
       length:1)) 

Visit this link very well explained

-1

我找到的AppDelegate我有錯:

UILabel.appearance().textColor = color 

所以解決的辦法就是把這個代碼在電池類:

override func awakeFromNib() { 
    super.awakeFromNib() 
    self.labelInformation.text = nil 
    self.labelInformation.textColor = nil 
} 
相關問題