Swift 5.5 AttributedString doesn't show in interface

Viewed 292

Here's the Swift 5.5 way to make an attributed string:

let s = "Hello"
var attrib = AttributedString(s)
if let range = attrib.range(of: "ell") {
    attrib[range].foregroundColor = .red
    self.label.attributedText = NSAttributedString(attrib)
}

The problem is that the label doesn't show any red characters. In fact, I can print self.label.attributedText and I can see that the red color attribute didn't even make it into the NSAttributedString. What's going on?

1 Answers

By default, Swift thinks you're applying the SwiftUI attributes, which UIKit doesn't understand. You have to specify what kind of attributed string attribute this is:

attrib[range].uiKit.foregroundColor = .red
//            ^^^^^
Related