【问题标题】:Change certain character within UIlabel [duplicate]更改 UIlabel 中的某些字符 [重复]
【发布时间】:2018-10-24 07:01:02
【问题描述】:

所以我有一个 UILabel ->

 mylabel = "ios is cool" 

(初始颜色为红色)

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

我将如何实现这一目标

【问题讨论】:

  • 谷歌NSAttributedString.

标签: ios iphone uilabel swift4


【解决方案1】:

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

    }

【讨论】:

    【解决方案2】:

    在 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;
    

    在斯威夫特中:

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-06-13
      • 2021-04-18
      • 1970-01-01
      • 2023-02-04
      • 1970-01-01
      • 2010-10-30
      • 1970-01-01
      • 2019-12-24
      相关资源
      最近更新 更多