Related: How To Customize Strings in Swift? Old but Gold: NSAttributedString
As default, SwiftUI allows customizing Text() view like below:
1 2 3 4 |
Text("CoffeeBreakCodes") .font(Font.system(size: 12)) .foregroundColor(Color.black) .underline() |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
struct CBCAttrText: UIViewRepresentable { var attributedText: NSAttributedString? init(_ attributedText: NSAttributedString?) { self.attributedText = attributedText } func makeUIView(context: Context) -> UILabel { return UILabel() } func updateUIView(_ uiView: UILabel, context: Context) { uiView.attributedText = attributedText } } |
Now, you can create an NSAttributedString and pass it to CBCAttrText.
1 2 3 4 5 6 7 8 9 10 11 12 |
var str = "SwiftUI: how to underline all text?" var attributedStr = NSMutableAttributedString(string: str) init() { attributedStr.addAttribute(NSAttributedString.Key.underlineStyle, value: NSUnderlineStyle.single.rawValue, range: NSRange(location: 0, length: attributedStr.length)) } var body: some View { CBCAttrText(attributedStr) } |

Pingback: How To Customize Strings in Swift? Old but Gold: NSAttributedString | Coffee Break Codes