I have a string like "abc1abc1"
.
What I want to do is bold each number of the string. I have drawn the code below. It works by separating each character of the string and putting them into an array. Then, in a loop, if each character contains an Int()
, the character is bolded.
However, the issue comes when the there are two of the same Int. In the string above, there are 2 characters of 1
, therefore the code will only bold the first character.
// Bold the numbers
let fullString = "abc1abc1"
let characters = Array(fullString)
let mutableString = NSMutableAttributedString(string: fullString)
for item in characters {
let string = String(item)
let decimalCharacters = CharacterSet.decimalDigits
let decimalRange = string.rangeOfCharacter(from: decimalCharacters)
if decimalRange != nil {
let str = NSString(string: fullString)
let range = str.range(of: string)
mutableString.addAttribute(NSAttributedStringKey.foregroundColor, value: UIFont.systemFont(ofSize: 18, weight: .heavy), range: range)
}
}
instructionsLabel.attributedText = mutableString
// characters = ["a", "b", "c", "1", "a", "b", "c", "1"]
// range of ints returns {3, 1} and {3, 1}
// range of ints SHOULD return {3, 1} and {7, 1}