How do you add a background color around each variable inside the interests variable? Just around text not the spaces.
var interests = \"\\(int01) \\(int02)
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.
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.
let attributedString = NSMutableAttributedString(string: interests)
attributedString.addAttribute(NSBackgroundColorAttributeName, value: yourColor, range: NSMakeRange(startOfWord, lengthOfWord))