Swift如何在标签中的文本周围添加背景颜色?
问题描述:
如何在兴趣变量内的每个变量周围添加背景色?文字周围没有空格.
How do you add a background color around each variable inside the interests variable? Just around text not the spaces.
var interests = "\(int01) \(int02) \(int03) \(int04) \(int05) \(int06)"
我希望它看起来像这样:
I want it to look like this:
答
您可以使用正则表达式查找除空格以外的任何内容,使用while循环在字符串中查找其出现的位置,并使用这些范围更改的背景色属性字符串:
You can use a regex to find anything but white spaces, use a while loop to find its occurrences in a string and use those ranges to change the background color of an attributed string:
快捷键4
let mutable = NSMutableAttributedString(string: interests)
var startIndex = interests.startIndex
while let range = interests.range(of: "\\S+", options: .regularExpression, range: startIndex..<interests.endIndex) {
mutable.addAttribute(.backgroundColor, value: UIColor.cyan, range: NSRange(range, in: interests))
startIndex = range.upperBound
}
label.attributedText = mutable
注意:如果您想在文本周围添加空格,可以将正则表达式更改为" \\S+ "
,并且不要忘记在原始兴趣字符串的开头和结尾添加空格.
Note: If you would like to add space around your text you can change your regex to " \\S+ "
and don't forget to add spaces at the begin and at the end of your original interests string.