I am trying to change colour for all numbers present in a string in swift
code.Example:
var mystring = \"abc 3423 opqrs 474598 lmno 343543\"
First, we need to find the ranges of number existed in the string. One way is to use regular expression
func findNumberRanges(string: String) -> [NSRange]{
let nsString = string as NSString
let regex = try? NSRegularExpression(pattern: "[0-9]+", options: [])
let matches = regex?.matches(in: string, options: .withoutAnchoringBounds, range: NSMakeRange(0, nsString.length))
return matches?.map{$0.range} ?? []
}
Then we can iterate through ranges of number to add the attribute, in this case to set red color.
func attributedNumberString(string: String, numberAttribute: [String: Any]) -> NSAttributedString{
let ranges = findNumberRanges(string: string)
let attributedString = NSMutableAttributedString(string: string)
for range in ranges{
attributedString.addAttributes(numberAttribute, range: range)
}
return attributedString
}
Here is how it is used:
let redColorAttribute = [ NSForegroundColorAttributeName: UIColor.red]
attributedNumberString(string: "6h40m", numberAttribute: redColorAttribute)