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\"
I did something like this for a project, So basically this check whether it's a number and save it's location then by using NSAttributedString, we can easily change the character color like this :-
class ViewController: UIViewController {
@IBOutlet weak var mylabel: UILabel!
let numbers = ["0","1","2","3","4","5","6","7","8","9"]
var mystring = "abc 3423 opqrs 474598 lmno 343543"
override func viewDidLoad() {
super.viewDidLoad()
let myAttributedString = NSMutableAttributedString(string: "\(self.mystring)")
var locations: [Int] = []
let characters = mystring.characters
var i = 0
for letter in characters {
i = i + 1
letter.debugDescription
if numbers.contains(String(letter)) {
locations.append(i)
}
}
for item in locations {
print(item)
let myRange = NSRange(location: item - 1, length: 1)
myAttributedString.addAttribute(NSForegroundColorAttributeName, value: UIColor.redColor(), range: myRange)
}
self.mylabel.attributedText = myAttributedString
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
Here is a screenShot