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

标签 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

        }

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

有人能帮忙吗?

最佳答案

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 , 而不是至少使用 countstring_to_color (或 for each loop )。如果明天您在其中添加一个字符串或删除一个字符串,您将遇到问题。

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

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

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

然后您必须迭代或使用 NSRegularExpression . 这是一个相关问题:Color all occurrences of string in swift

关于arrays - 更改文本颜色时的 Swift 4 数组问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49232009/

相关文章:

javascript - Shift 字符串 左右循环

c - 通过多个函数访问数组

ios - Swift 中的 componentsSeparatedByString 方法

swift - 使用两个集合类型参数查找项目索引

arrays - Xcode、Parse - 将数组对象中的值存储在本地数组中

PHP:如何将数据库结果(字符串)作为数组(使用爆炸)按顺序添加到空数组元素

arrays - 这个通过引用传递数组的示例在 Perl 中是如何工作的?

arrays - 查找正在运行的进程的 PID 并将其存储为数组

swift - 删除饼图图例中的文本 'DataSet'

ios - Swift 4 - Alamofire - 如何根据请求禁用缓存