我只想更改Label的字符串中某些单词的颜色。
我想做的是:
但它不起作用,它说:' NSMutableRLEArray replaceObjectsInRange:withObject:length :: out of bounds'
所以我需要一个建议来做这个简单的事情,我需要一个技巧来做到这一点。你们可以发送你的方式。
答案 0 :(得分:6)
试试这个,当你尝试获取字符串的范围时,你的属性字符串没有值。在此之前,您必须为属性字符串赋予字符串值。你
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")
答案 1 :(得分:0)
它超出范围,因为在您尝试设置属性时myMutableString
为空。请尝试改为:
let myMutableString = NSMutableAttributedString.init(string: label.text)
答案 2 :(得分:0)
使用第一种颜色
创建attributedString1
let attributedString1 = NSAttributedString(string: "robert plant ", attributes: [NSForegroundColorAttributeName: color1])
使用第二种颜色创建attributedString2
let attributedString1 = NSAttributedString(string: "with queen", attributes: [NSForegroundColorAttributeName: color2])
将它们添加到myMutableString
myMutableString.append(attributedString1)
myMutableString.append(attributedString1)