Swift how to add background color just around text in a label?

后端 未结 3 931
逝去的感伤
逝去的感伤 2021-01-25 00:23

How do you add a background color around each variable inside the interests variable? Just around text not the spaces.

var interests = \"\\(int01)     \\(int02)          


        
3条回答
  •  没有蜡笔的小新
    2021-01-25 00:56

    You can use a regex to find anything but white spaces, use a while loop to find its occurrences in a string and use those ranges to change the background color of an attributed string:

    Swift 4

    let mutable = NSMutableAttributedString(string: interests)
    var startIndex = interests.startIndex
    while let range = interests.range(of: "\\S+", options: .regularExpression, range: startIndex..

    Note: If you would like to add space around your text you can change your regex to " \\S+ " and don't forget to add spaces at the begin and at the end of your original interests string.

提交回复
热议问题