Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift 5.5 AttributedString doesn't show in interface

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?

like image 569
matt Avatar asked Oct 27 '25 10:10

matt


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
//            ^^^^^
like image 179
matt Avatar answered Oct 30 '25 05:10

matt