I have a string such as the following:
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.
You could use a regular expression:
let regex = try! NSRegularExpression(pattern: "[\\*]{1}[^\\*]+[\\*]{1}")
regex
is a regular expression that matches:
[\\\\*]{1}
. Followed by, [^\\\\*]+
. Followed by, [\\\\*]{1}
Let's get the matches:
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: rg)
let ranges = matches.map {$0.range}
Let's create a mutable attributed string:
let attributedString = NSMutableAttributedString(string: str)
And add the foregroundColor
attribute to the matches, and remove the asterisks:
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
label.attributedText = attributedString
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.