更改UIlabel

时间:2018-10-24 07:01:02

标签: ios iphone uilabel swift4

所以我有一个UILabel->

 mylabel = "ios is cool" 

(初始颜色为红色)

现在我想将'ios'文本颜色更改为蓝色,其余文本应仅为红色。

我将如何实现

2 个答案:

答案 0 :(得分:0)

在Objective-C中:

NSString *text = @"ios is cool";
NSRange rang = [strWhole rangeOfString:@"ios"];
NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:text];
[attributedString addAttribute:NSForegroundColorAttributeName 
             value:[UIColor blueColor] 
             range:rang];
mylabel.attributedText = attributedString;

在Swift中:

let text = "ios is cool"
let rang = text.range(of:"ios")
let attributedString = NSMutableAttributedString(string: text)
attributedString.addAttribute(.foregroundColor, value: UIColor.blue, range:rang)
mylabel.attributedText = attributedString

答案 1 :(得分:0)

设置您的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

    }