2017-05-28 39 views
0

我只是想改變一些字的顏色在我的標籤的字符串。更改某個單詞的顏色的UILabel

我想要做的是:

What I want to do is:

林如何試圖做:

但它不工作,它說:「NSMutableRLEArray replaceObjectsInRange:withObject:長度::出的界限

所以我需要一個建議做這一件容易的事情,我需要一個把戲做到這一點。你們可以發送你的路。

+0

請發表您的代碼文字,而不是圖像。您無法從圖像中搜索或引用代碼。 – rmaddy

+0

@maddy我的不好,抱歉。 – Alper

回答

2

試試這個,你的屬性串有當您嘗試得到字符串的範圍沒有價值。在此之前,你必須給屬性字符串一個字符串值。你

let descriptionLabel: UILabel = { 

     let label = UILabel() 

     // String variable containing the text. 
     let fullString = "mehmet alper tabak" 

     // Choose wwhat you want to be colored. 
     let coloredString = "alper" 

     // Get the range of the colored string. 
     let rangeOfColoredString = (fullString as NSString).range(of: coloredString) 

     // Create the attributedString. 
     let attributedString = NSMutableAttributedString(string:fullString) 
     attributedString.setAttributes([NSForegroundColorAttributeName: UIColor.red], 
           range: rangeOfColoredString) 
     label.attributedText = attributedString 
    return label 
    }() 

    descriptionLabel.frame = CGRect(x: 50, y: 50, width: 140, height: 100) 
    self.view.addSubview(descriptionLabel) 

或者你可以做一個UILabel的擴展。

extension UILabel { 

     func colorString(text: String?, coloredText: String?, color: UIColor? = .red) { 

     let attributedString = NSMutableAttributedString(string: text!) 
     let range = (text! as NSString).range(of: coloredText!) 
     attributedString.setAttributes([NSForegroundColorAttributeName: color!], 
           range: range) 
     self.attributedText = attributedString 
    } 

使用它。

 self.testLabel.colorString(text: "mehmet alper tabak", 
          coloredText: "alper") 
+0

謝謝你,這就是它最簡單的解決方案。現在我沒有問題,並且在我的腦海裏有任何問號^ _ ^ – Alper

0

這是出界,因爲myMutableString是在你試圖設置屬性的時間空。嘗試改爲:

let myMutableString = NSMutableAttributedString.init(string: label.text) 
+0

感謝您的回覆。有效!但我不知道你有另一種解決方案嗎?除了我的方式? – Alper

+0

什麼這將是一個靜態的東西,如「歡迎@username」。在這種情況下,它的長度不是特別的。 – Alper

+0

創建屬性串'讓attributedString = NSAttributedString(字符串:用戶名,屬性:歸因)',追加到可變'myMutableString.append(attributedString)' –

0

第1顏色

let attributedString1 = NSAttributedString(string: "robert plant ", attributes: [NSForegroundColorAttributeName: color1]) 

創建attributedString1與第二顏色創建attributedString2

let attributedString1 = NSAttributedString(string: "with queen", attributes: [NSForegroundColorAttributeName: color2]) 

它們添加到myMutableString

myMutableString.append(attributedString1) 
myMutableString.append(attributedString1)