0

so I have a UILabel ->

 mylabel = "ios is cool" 

( initial color is red)

now I want to change the text 'ios' color to blue, the remaining text should be in red color only.

How will I achieve this

sunny
  • 61
  • 5

2 Answers2

0

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

In 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
rmaddy
  • 314,917
  • 42
  • 532
  • 579
Ron Gahlot
  • 1,396
  • 8
  • 18
0

Set Your UILabel text

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

Write this func in your 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

    }
Sabbir Ahmed
  • 351
  • 1
  • 13