How to create an attributed string (NSAttributedString) in Swift?
Hi everyone! I'm new to Swift and trying to make text with different formatting in UILabel. For example, one word should be bold, another red, and a third underlined. I know there's NSAttributedString for this, but I can't figure out how to use it.
I tried writing this code, but it doesn't work:
```swift
let label = UILabel()
label.text = "Hello, world!"
label.textColor = UIColor.red // I want only part of the text to be red
```
Then I tried using NSAttributedString, but got confused with the syntax. Here's what I wrote:
```swift
let attributedString = NSAttributedString(string: "Hello, world!")
attributedString.addAttribute(.foregroundColor, value: UIColor.red, range: NSRange(location: 0, length: 7))
label.attributedText = attributedString
```
But Xcode
No answers yet.
Log in to leave an answer