How to change colour of all numbers in a string in swift

前端 未结 6 635
灰色年华
灰色年华 2021-01-14 11:24

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\"
         


        
6条回答
  •  感情败类
    2021-01-14 11:58

    Here's an extension using Swift 5 using Zig's answer as reference:

      extension String {
    
        func changeColorForNumbers() -> NSMutableAttributedString {
            let red = [NSAttributedString.Key.foregroundColor: UIColor.red]
    
            let myAttributedString = NSMutableAttributedString()
            for letter in self.unicodeScalars {
                let myLetter : NSAttributedString
                if CharacterSet.decimalDigits.contains(letter) {
                    myLetter = NSAttributedString(string: "\(letter)", attributes: orange)
                } else {
                    myLetter = NSAttributedString(string: "\(letter)")
                }
                myAttributedString.append(myLetter)
            }
    
            return myAttributedString
        }
    
    }
    

提交回复
热议问题