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

后端 未结 3 841
逝去的感伤
逝去的感伤 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..<interests.endIndex) {
        mutable.addAttribute(.backgroundColor, value: UIColor.cyan, range: NSRange(range, in: interests))
        startIndex = range.upperBound
    }
    label.attributedText = mutable
    

    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.

    0 讨论(0)
  • 2021-01-25 01:01

    What you can do is use a UICollectionView with cells that have labels that span the entire cell. Each cell then corresponds to individual words. That way you can set either the label or the cell background color to whatever you want.

    For ease of implementation, I would turn your interests variable into an array of strings. That way you can easily count the number of cells you need and give each cell the right string.

    0 讨论(0)
  • 2021-01-25 01:05
    let attributedString = NSMutableAttributedString(string: interests)
    attributedString.addAttribute(NSBackgroundColorAttributeName, value: yourColor, range: NSMakeRange(startOfWord, lengthOfWord))
    
    0 讨论(0)
提交回复
热议问题