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

前端 未结 6 631
灰色年华
灰色年华 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:50

    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)
    

提交回复
热议问题