How to use Attributed String in SwiftUI

iOS 15 and Swift 5.5

Text now supports markdown and also you can create custom attributes:

enter image description here

You can even get defined attributes remotely like:

enter image description here


iOS 13 and 14

You can combine multiple Text objects together with a simple + operator and that will handle some of the attributions:

enter image description here

Each one can have multiple and specific modifiers


A fully supported fallback!

Since it doesn’t support directly on Text (till iOS 15), you can bring the UILabel there and modify it in anyway you like:

Implementation:

struct UIKLabel: UIViewRepresentable {

    typealias TheUIView = UILabel
    fileprivate var configuration = { (view: TheUIView) in }

    func makeUIView(context: UIViewRepresentableContext<Self>) -> TheUIView { TheUIView() }
    func updateUIView(_ uiView: TheUIView, context: UIViewRepresentableContext<Self>) {
        configuration(uiView)
    }
}

Usage:

var body: some View {
    UIKLabel {
        $0.attributedText = NSAttributedString(string: "HelloWorld")
    }
}

Leave a Comment