我有一个带有如下所示字符串的标签。我希望secondVariable
是一种不同的颜色。我想我明白了如何改变颜色。我的问题是获得secondVariable
。
let str = "\(firstVariable) some random text \(secondVariable)"
let secondVariableRange = str.range(???)
let secondVariableNSRange = NSRange(secondVariableRange, in: str)
let attributedString = NSMutableAttributedString.init(string:
"\(firstVariable) some random text \(secondVariable)")
attributedString.addAttribute(.foregroundColor, value: UIColor.white,
range: NSRange(secondVariableNSRange, in: attributedString)
答案 0 :(得分:0)
有一种比处理范围更简单的方法。将您的属性字符串构建成碎片。
let attributedString = NSMutableAttributedString(string:
"\(firstVariable) some random text ")
let attrs: [NSAttributedStringKey : Any] = [ .foregroundColor: UIColor.white ]
let secondString = NSAttributedString(string: "\(secondVariable)", attributes: attrs)
attributedString.append(secondString)
但如果您真的想要获得范围,请使用:
let secondVariableRange = (str as NSString).range(of: "\(secondVariable)")