ios - 如何更改 UILabel 中字符类型(而非字符串)的颜色?

标签 ios swift

<分区>

如果我有一个带有如下字符串的 UILabel:

func makeLabel() {
    textLabel.text = "3abc 3xyz apple3 3banana 3tree pluto3"
    textLabel.textColor = UIColor.black
    ...
}

如何仅更改“3”字符的颜色?这里还有其他问题看起来非常相似,但涉及字符串替换,而不是字符替换。

最佳答案

您应该使用 textLabel.attributedText 而不是 textLabel.text

要了解 NSAttributedText 的工作原理:阅读 the documentation of NSAttributedTextthis stack overflow answer

所以一个可能的解决方案是遍历字符串中的所有字符,如果字符是“3”则添加红色前景色

swift 3:

textLabel.attributedText = "3ab apple3 3bana".characters.reduce(NSMutableAttributedString()) {
    $0.append(
        NSAttributedString(
            string: String($1),
            attributes: [
                NSForegroundColorAttributeName: $1 == "3" ? UIColor.red : .black
            ]
        )
    )
    return $0
}

swift 4:

textLabel.attributedText = "3ab apple3 3bana".reduce(NSMutableAttributedString()) {
    $0.append(
        NSAttributedString(
            string: String($1),
            attributes: [
                .foregroundColor: $1 == "3" ? UIColor.red : .black
            ]
        )
    )
    return $0
}

不是重复的

我认为这不是 Color all occurrences of string in swift 的重复,因为 StringsCharacters 在 Swift 中是两个不同的东西!

关于ios - 如何更改 UILabel 中字符类型(而非字符串)的颜色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45606070/

相关文章:

ios - KVO keyPathsForValuesAffecting 不起作用

ios - 在 Swift 中使用对象过滤二维数组

ios - Foreach 如果所有字段都是 "0",返回一个 View

ios - Swift 中数组的直方图

ios - 在 Swift 中将 Alamofire 调用包装到自定义对象中?

ios - 通过在 FirstViewController 中输入城市名称来更改 UITableView 数据

swift - 快速编辑 TableView 单元格中的 TextView

ios - 将临时应用提交到Appstore/iTunesConnect

javascript - 圆弧未在 Safari 中的 2D 上下文中呈现

javascript - react native 运行ios类型错误: invalid data