How To Use NSAttributedString in SwiftUI: Hack It!


Related: How To Customize Strings in Swift? Old but Gold: NSAttributedString

As default, SwiftUI allows customizing Text() view like below:

But when you try to show an NSAttributedString directly in Text(), you see an error:

Let’s try to hack it!

A custom UIViewRepresentable class will help us to avoid the restrictions of SwiftUI. Create a custom swift struct that inherits UIViewRepresentable class.

By overriding its makeUIView and updateUIView functions, we define that our view is a UILabel.

Now, you can create an NSAttributedString and pass it to CBCAttrText.


Leave a comment

Your email address will not be published. Required fields are marked *

One thought on “How To Use NSAttributedString in SwiftUI: Hack It!