更改文本颜色时Swift 4数组问题

时间:2018-03-12 09:37:56

标签: arrays swift

我有一个字符串,我想更改该字符串中两个单词的颜色。所以,我创建了一个函数

func setup()
    {

        let main_string = "By continuing you agree to our Term of use and Privacy Policy "

        var string_to_color = ["By continuing you agree to our","and"]

        for i in 0..<2
        {

            let range = (main_string as NSString).range(of: string_to_color[i])

            let attributedString = NSMutableAttributedString.init(string:main_string)

            attributedString.addAttribute(NSAttributedStringKey.foregroundColor, value: UIColor.black , range: range)

            privacyL.attributedText = attributedString

        }

但是,它只会改变第二个单词的颜色而不会改变第一个单词的颜色。

有人可以帮忙吗?

2 个答案:

答案 0 :(得分:2)

let main_string = "By continuing you agree to our Term of use and Privacy Policy "

var string_to_color = ["By continuing you agree to our","and"]

for i in 0..<2
{

    let range = (main_string as NSString).range(of: string_to_color[i])

    let attributedString = NSMutableAttributedString.init(string:main_string)

    attributedString.addAttribute(NSAttributedStringKey.foregroundColor, value: UIColor.black , range: range)

    privacyL.attributedText = attributedString

}

每次privacyL.attributedText都覆盖,所以你只得到最后一次迭代的“结果”。

相反,请执行:

let attributedString = NSMutableAttributedString.init(string:main_string)
for i in 0..<2
{
    let range = (main_string as NSString).range(of: string_to_color[i])
    attributedString.addAttribute(NSAttributedStringKey.foregroundColor, value: UIColor.black , range: range)

}
privacyL.attributedText = attributedString

现在,下一期: 不要进行循环for i in 0..<2,而应至少使用count string_to_color(或for each loop)。如果明天你在其中添加一个字符串或删除一个字符串,你将遇到一个问题。

同样range(of:)将返回找到的第一个出现,所以如果你有:

let main_string = "and and"
var string_to_color = ["something", "and"]

只有第一个“和”会被着色。

然后您必须迭代或使用NSRegularExpression。 以下是相关问题:Color all occurrences of string in swift

答案 1 :(得分:0)

只想添加Larme的答案。您可以创建String的扩展名,它将负责字符串着色

extension String {
    func colored(_ strings: [String], with color: UIColor) -> NSAttributedString {
        let attributedString: NSMutableAttributedString = NSMutableAttributedString(string: self)
        for string in strings {
            let range = (self as NSString).range(of: string)
            attributedString.addAttribute(NSAttributedStringKey.foregroundColor, value: color , range: range)
        }
        return attributedString
    }
}

现在您可以在代码中的任何位置使用它,例如:

let main_string = "By continuing you agree to our Term of use and Privacy Policy "
let string_to_color = ["By continuing you agree to our","and"]
privacyL.attributedText = main_string.colored(string_to_color, with: UIColor.red)