Swift如何在标签中的文本周围添加背景颜色? [英] Swift how to add background color just around text in a label?

查看:147
本文介绍了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.

这篇关于Swift如何在标签中的文本周围添加背景颜色?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆