我有一个如下字符串:
let myString = "This is my *awesome* label which *should* change color";
我需要做的是将此文本添加到UILabel,将文本颜色更改为橙色,其中文本的部分被星号包围,并在显示之前删除星号。
我该怎么做?
我知道您可以使用标签的属性文本来组合不同颜色的文本,但是不确定如何分解字符串以实现所需的行为。
答案 0 :(得分:1)
您可以使用正则表达式:
let regex = try! NSRegularExpression(pattern: "[\\*]{1}[^\\*]+[\\*]{1}")
regex
是一个符合以下条件的正则表达式:
[\\*]{1}
。随后,[^\\*]+
。随后,[\\*]{1}
让我们得到比赛:
let str = "This is my *awesome* label which *should* change color"
let length = (str as NSString).length
let rg = NSRange(location: 0, length: length)
let matches = regex.matches(in: str, range: rg)
let ranges = matches.map {$0.range}
让我们创建一个可变的属性字符串:
let attributedString = NSMutableAttributedString(string: str)
然后将foregroundColor
属性添加到匹配项中,并删除星号:
let attribute = [NSAttributedString.Key.foregroundColor: UIColor.orange]
let startIndex = str.startIndex
ranges.reversed()
.forEach{ range in
attributedString.addAttributes(attribute, range: range)
let start = str.index(startIndex, offsetBy: range.lowerBound.advanced(by: 1))
let end = str.index(startIndex, offsetBy: range.upperBound.advanced(by: -1))
let withoutAsterisk = String(str[start..<end])
attributedString.replaceCharacters(in: range, with: withoutAsterisk)
}
并设置标签的attributedText
label.attributedText = attributedString