我只是想改變一些字的顏色在我的標籤的字符串。更改某個單詞的顏色的UILabel
我想要做的是:
但它不工作,它說:「NSMutableRLEArray replaceObjectsInRange:withObject:長度::出的界限
所以我需要一個建議做這一件容易的事情,我需要一個把戲做到這一點。你們可以發送你的路。
我只是想改變一些字的顏色在我的標籤的字符串。更改某個單詞的顏色的UILabel
我想要做的是:
但它不工作,它說:「NSMutableRLEArray replaceObjectsInRange:withObject:長度::出的界限
所以我需要一個建議做這一件容易的事情,我需要一個把戲做到這一點。你們可以發送你的路。
試試這個,你的屬性串有當您嘗試得到字符串的範圍沒有價值。在此之前,你必須給屬性字符串一個字符串值。你
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")
謝謝你,這就是它最簡單的解決方案。現在我沒有問題,並且在我的腦海裏有任何問號^ _ ^ – Alper
這是出界,因爲myMutableString
是在你試圖設置屬性的時間空。嘗試改爲:
let myMutableString = NSMutableAttributedString.init(string: label.text)
第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)
請發表您的代碼文字,而不是圖像。您無法從圖像中搜索或引用代碼。 – rmaddy
@maddy我的不好,抱歉。 – Alper