0

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}
Annabelle Sykes
  • 121
  • 1
  • 2
  • 10

1 Answers1

1

Try this:

let fullString = "abc1abc1"
let range = NSRange(location: 0, length: (fullString as NSString).length)
let mutableString = NSMutableAttributedString(string: fullString)
let regex = try! NSRegularExpression(pattern: "[0-9]")
let matches = regex.matches(in: fullString, range: range)

for match in matches {
    mutableString.addAttributes([.font: UIFont.systemFont(ofSize: 18, weight: .heavy)], range: match.range)
}

instructionsLabel.attributedText = mutableString
ielyamani
  • 17,807
  • 10
  • 55
  • 90