Change color of text on parts of UILabel that are surrounded by asterisks

codeman

New Member
#1
I have a string such as the following:
Mã:
let myString = "This is my *awesome* label which *should* change color";
What I need to do is add this text to a UILabel, changing the text color to orange where the parts of the text are surrounded by asterisks, and removing the asterisks before displaying.

How can I accomplish this?

I know you can combine different colors of text using attributed text for labels, but not sure how to break up the string to achieve the desired behavior.
 

Admin

Administrator
Thành viên BQT
#2
You could use a regular expression:
Mã:
let regex = try! NSRegularExpression(pattern: "[\\*]{1}[^\\*]+[\\*]{1}")
regex is a regular expression that matches:

  • One asterisk: [\\*]{1}. Followed by,
  • One or more characters that are not an asterisk: [^\\*]+. Followed by,
  • One asterisk: [\\*]{1}
Let's get the matches:

Mã:
let str = "This is my *awesome* label which *should* change color"
let length = (str as NSString).length
let rg = NSRange(location: 0, length: length)
let matches = regex.matches(in: str, range: range)
let ranges = matches.map {$0.range}
Let's create a mutable attributed string:
Mã:
let attributedString = NSMutableAttributedString(string: str)
And add the foregroundColor attribute to the matches, and remove the asterisks:
Mã:
let attribute = [NSAttributedString.Key.foregroundColor: UIColor.orange]
let startIndex = str.startIndex
ranges.reversed()
    .forEach{ range in
        attributedString.addAttributes(attribute, range: range)
        let start = str.index(startIndex, offsetBy: range.lowerBound.advanced(by: 1))
        let end = str.index(startIndex, offsetBy: range.upperBound.advanced(by: -1))
        let withoutAsterisk = String(str[start..<end])
        attributedString.replaceCharacters(in: range, with: withoutAsterisk)
}
And set the attributedText of your label
Mã:
label.attributedText = attributedString
 
OP
OP
C

codeman

New Member
#3
Nice bit of work (voted), although I'm more inclined to outline a solution and give some of the pieces rather than providing a fully coded solution.
 

Từ khóa phổ biến

You are using an out of date browser. It may not display this or other websites correctly.
You should upgrade or use an alternative browser.

Top