NSMutableAttributedString的可变大小范围

时间:2018-05-24 15:50:25

标签: swift range swift4 nsmutableattributedstring

我有一个带有如下所示字符串的标签。我希望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)

1 个答案:

答案 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)")