首页 > 解决方案 > 更改 UIlabel 中的某些字符

问题描述

所以我有一个 UILabel ->

 mylabel = "ios is cool" 

(初始颜色为红色)

现在我想将文本“ios”的颜色更改为蓝色,剩余的文本应该只有红色。

我将如何实现这一目标

标签: iosiphoneuilabelswift4

解决方案


设置你的 UILabel 文本

let text = textColorChange(fullText: "ios is cool", changeColorText: "ios")
mylabel.attributedText = text

在你的 UIViewController 中写这个函数

func textColorChange(fullText: String, changeColorText: String) -> NSMutableAttributedString {

        let attributedString: NSMutableAttributedString = NSMutableAttributedString(string: changeColorText)
        let pattern = fullText.lowercased
        let range: NSRange = NSMakeRange(0, changeColorText.count)

        let regex = try! NSRegularExpression(pattern: pattern(), options: NSRegularExpression.Options())

        regex.enumerateMatches(in: changeColorText.lowercased(), options: NSRegularExpression.MatchingOptions(), range: range) { (textCheckingResult, matchingFlags, stop) -> Void in
            let subRange = textCheckingResult?.range
            attributedString.addAttribute(NSAttributedString.Key.foregroundColor, value: UIColor.blue, range: subRange!)
        }

        return attributedString

    }

推荐阅读