How to use Attributed String in SwiftUI
Asked Answered
A

11

77

How to use AttributedString in SwiftUI. There is no API available to use AttributedString in Text

Apuleius answered 30/12, 2019 at 12:48 Comment(0)
C
105

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")
    }
}
Colwin answered 30/12, 2019 at 12:57 Comment(6)
Is there a way to make one of those Texts clickable? tapGesture doesn't seem suitable as it's returning some View and not Text?Watercolor
+1 for More native but less access. It covers some length in formatting text without adding extra and complicated codes.Engagement
Usage: "Argument passed to call that takes no arguments"Lionel
SwiftUI 2.0 has a struct named Label. You probably forgot to implement your own Label and it conflicted with the original version @IxxColwin
The "more native" version is fine for simple things but falls apart for things like pluralization and localized strings. SwiftUI doesn't appear to have any offering for this yet.Porras
@MojtabaHosseini - How to enable alignment on UIKLabel ? Have tried wrapping on stacks and own View nothing appears to work.Obelize
D
41

The idea of attributed string is string with attributes. In SwiftUI this idea is realised with Text attributed modifiers and + operator. Like in the below example:

SwiftUI Text with attributes

Group {
    Text("Bold")
        .fontWeight(.bold) +
    Text("Underlined")
        .underline() +
    Text("Color")
        .foregroundColor(Color.red)
}
Dishpan answered 30/12, 2019 at 13:2 Comment(4)
This is definitely not good if you are supporting more than one language.Flaunch
Here if we use like this and if we want to add click on Color or any other text we can notOswaldooswalt
Seems though like there is a possibility there to create an attributed string type system in pure swift UI with this conceptPorras
@Dishpan But in multiline it doesn't work properly. I have these text in VStack with leading alignment but the texts are not leading alignmentDegradable
G
40

iOS 15

We finally get AttributedString! It's really easy to use.

Multiple Attributed Strings with different attributes

struct ContentView: View {
    var body: some View {
        VStack(spacing: 40) {
            
            /// Note: You can replace `$0` with `string in string`
            
            VStack {
                Text("Regular")
                Text("Italics") { $0.font = Font.system(size: 17).italic() }
                Text("Bold") { $0.font = Font.system(size: 17).bold() }
                Text("Strikethrough") { $0.strikethroughStyle = Text.LineStyle(pattern: .solid, color: .red) }
                Text("Code") { $0.font = Font.system(size: 17, design: .monospaced) }
                Text("Foreground Color") { $0.foregroundColor = Color.purple }
                Text("Background Color") { $0.backgroundColor = Color.yellow }
                Text("Underline") { $0.underlineColor = Color.green }
            }
            
            VStack {
                Text("Kern") { $0.kern = CGFloat(10) }
                Text("Tracking") { $0.tracking = CGFloat(10) }
            }
            
            VStack {
                Text("Baseline Offset") { $0.baselineOffset = CGFloat(10) }
                Text("Link") { $0.link = URL(string: "https://apple.com") }
            }
        }
    }
}

/// extension to make applying AttributedString even easier
extension Text {
    init(_ string: String, configure: ((inout AttributedString) -> Void)) {
        var attributedString = AttributedString(string) /// create an `AttributedString`
        configure(&attributedString) /// configure using the closure
        self.init(attributedString) /// initialize a `Text`
    }
}

To apply attributes to specific ranges, use the range(of:options:locale:) method.

Attributed String with different colors

struct ContentView: View {
    var body: some View {
        Text("Some Attributed String") { string in
            string.foregroundColor = .blue
            if let range = string.range(of: "Attributed") { /// here!
                string[range].foregroundColor = .red
            }
        }
    }
}

See my article for more details. Also, you can use Markdown!

Gesso answered 8/6, 2021 at 14:46 Comment(3)
Thanks for putting in the work; this was immensely useful. I now can use user-defined custom fonts in my SwiftUI project with string.font = Font.custom("Hackles", size: 16) though I wish Apple was providing an easier way of adding custom fonts.Baresark
@Baresark You could extend Font to add your your static function to use your custom font, so that you don't have to hardcode just inside that function and use it everywhere else in the codePowell
Would it work with TextField?Allison
P
16

There are many answers to this that all use UILabel or UITextView. I was curious if it would be possible to create a native SwiftUI implementation that did not rely on any UIKit functionality. This represents an implementation that fits my current needs. It's FAR from a complete implementation of the NSAttributedString spec, but it's definitely good enough for the most basic needs. The constructor for NSAttributedString that takes an HTML string is a custom category I made, very easy to implement. If someone wants to run with this and create a more robust and complete component, you'd be my hero. Sadly I don't have the time for such a project.

//
//  AttributedText.swift
//
import SwiftUI

struct AttributedTextBlock {
    let content: String
    let font: Font?
    let color: Color?
}

struct AttributedText: View {
    var attributedText: NSAttributedString?
    
    private var descriptions: [AttributedTextBlock] = []
    
    init(_ attributedText: NSAttributedString?) {
        self.attributedText = attributedText
        
        self.extractDescriptions()
    }
    
    init(stringKey: String) {
        self.init(NSAttributedString(htmlString: NSLocalizedString(stringKey, comment: "")))
    }
    
    init(htmlString: String) {
        self.init(NSAttributedString(htmlString: htmlString))
    }
    
    private mutating func extractDescriptions()  {
        if let text = attributedText {
            text.enumerateAttributes(in: NSMakeRange(0, text.length), options: [], using: { (attribute, range, stop) in
                let substring = (text.string as NSString).substring(with: range)
                let font =  (attribute[.font] as? UIFont).map { Font.custom($0.fontName, size: $0.pointSize) }
                let color = (attribute[.foregroundColor] as? UIColor).map { Color($0) }
                descriptions.append(AttributedTextBlock(content: substring,
                                                        font: font,
                                                        color: color))
            })
        }
    }
    
    var body: some View {
        descriptions.map { description in
            Text(description.content)
                .font(description.font)
                .foregroundColor(description.color)
        }.reduce(Text("")) { (result, text) in
            result + text
        }
    }
}

struct AttributedText_Previews: PreviewProvider {
    static var previews: some View {
        AttributedText(htmlString: "Hello! <b>World</b>")
    }
}
Porras answered 31/10, 2020 at 22:18 Comment(6)
This is excellent work! I added a scrollview and was off to the races! I have persisted data objects that are 40K+ byte NSAttributedStrings and the view opens them up with no delays (they were taking 5 or more seconds to appear before). Would upvote more than once if I could.Bireme
Nice work! Unfortunately getting logs: AttributeGraph: cycle detected through attribute X when using it in a View, eventually leading to a crash :/Shanel
Interesting, yeah I'm not sure why, it could be that your attributed string has a use case that the code does not account for. If you're able to find the bug, post a gist of it and I'll update the answer with the bug fix.Porras
Does not work in iOS 15, Xcode 13.3.1. Preview simply shows: "Hello! <b>World</b>"Waltner
@Waltner This class will not automatically turn an HTML string into an attributed string. you will need to write your own extension to do that. BTW this might be obsolete now since I believe iOS 15 introduced AttributedString support to the regular Text object. In addition I believe markdown is now supported which is superior to HTML for simple things like bold/italics.Porras
Compiler complained on self.init(NSAttributedString(htmlString: htmlString)) Changed to self.init(NSAttributedString(string: htmlString)Happiness
O
13

if you want to achieve dynamic height text with NSAttributedString you can use this :

Implementation:

 struct TextWithAttributedString: View {

    var attributedText: NSAttributedString
    @State private var height: CGFloat = .zero

    var body: some View {
        InternalTextView(attributedText: attributedText, dynamicHeight: $height)
            .frame(minHeight: height)
    }

    struct InternalTextView: UIViewRepresentable {

        var attributedText: NSAttributedString
        @Binding var dynamicHeight: CGFloat

        func makeUIView(context: Context) -> UITextView {
            let textView = UITextView()
            textView.textAlignment = .justified
            textView.isScrollEnabled = false
            textView.isUserInteractionEnabled = false
            textView.showsVerticalScrollIndicator = false
            textView.showsHorizontalScrollIndicator = false
            textView.allowsEditingTextAttributes = false
            textView.backgroundColor = .clear
            textView.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)
            textView.setContentCompressionResistancePriority(.defaultLow, for: .vertical)
            return textView
        }

        func updateUIView(_ uiView: UITextView, context: Context) {
            uiView.attributedText = attributedText
            DispatchQueue.main.async {
                dynamicHeight = uiView.sizeThatFits(CGSize(width: uiView.bounds.width, height: CGFloat.greatestFiniteMagnitude)).height
            }
        }
    }
}

usage:

    VStack {
       TextWithAttributedString(attributedText: viewModel.description)
         .padding([.leading, .trailing], self.horizontalPadding)
         .layoutPriority(1)
         .background(Color.clear)
    }
    .transition(.opacity)
    .animation(.linear)
Ornis answered 30/12, 2020 at 10:32 Comment(1)
Works like a charm! Way better than the first option of this post.Gossamer
W
4

To add only one different style for iOS 14 this worked for me:

struct ItalicTextView: View {
  let text: String
  let italicText: String

  var body: some View {
    let array = text.components(separatedBy: italicText)
    array.reduce(Text(""), {
      if $1 == array.last {
        return $0 + Text($1)
      }
      return $0 + Text($1) + Text(italicText).italic()
    })
  }
}

Usage:

 var body: some View {
 HStack(alignment: .center, spacing: 0) {
    ItalicTextView(text: notification.description, italicText: "example")
      .multilineTextAlignment(.leading)
      .fixedSize(horizontal: false, vertical: true)
      .padding(.vertical, 16)
      .padding(.horizontal, 8)
  }
}

}

Whirly answered 27/10, 2021 at 19:23 Comment(0)
T
3

Since iOS 15, Text can have an AttributedString parameter.

No UIViewRepresentable necessary

Since NSAttributedString can be created from HTML, the process is straight forward:

import SwiftUI

@available(iOS 15, *)
struct TestHTMLText: View {
    var body: some View {
        let html = "<h1>Heading</h1> <p>paragraph.</p>"

        if let nsAttributedString = try? NSAttributedString(data: Data(html.utf8), options: [.documentType: NSAttributedString.DocumentType.html], documentAttributes: nil),
           let attributedString = try? AttributedString(nsAttributedString, including: \.uiKit) {
            Text(attributedString)
        } else {
            Text(html)
        }
    }
}

@available(iOS 15, *)
struct TestHTMLText_Previews: PreviewProvider {
    static var previews: some View {
        TestHTMLText()
    }
}

The code renders this:

Rendered HTML example

Terrorist answered 28/1, 2023 at 8:47 Comment(0)
G
2
  1. Works for MacOS
  2. Works MUCH FASTER than SwiftUI's Text(someInstanceOf_AttributedString)
  3. Ability to select text WITOUT resetting of font attributes on click or text selection
import SwiftUI
import Cocoa

@available(OSX 11.0, *)
public struct AttributedText: NSViewRepresentable {
    private let text: NSAttributedString
    
    public init(attributedString: NSAttributedString) {
        text = attributedString
    }
    
    public func makeNSView(context: Context) -> NSTextField {
        let textField = NSTextField(labelWithAttributedString: text)
        textField.isSelectable = true
        textField.allowsEditingTextAttributes = true // Fix of clear of styles on click
        
        textField.preferredMaxLayoutWidth = textField.frame.width
        
        return textField
    }
    
    public func updateNSView(_ nsView: NSTextField, context: Context) {
        nsView.attributedStringValue = text
    }
}
Guncotton answered 22/12, 2021 at 3:56 Comment(0)
P
1

Try this, it works for me.

var body: some View {
    let nsAttributedString = NSAttributedString(string: "How to use Attributed String in SwiftUI \n How to use Attributed String in SwiftUIHow to use Attributed String in SwiftUI", attributes: [.font: UIFont.systemFont(ofSize: 17), .backgroundColor: UIColor.red])
    let attributedString = try! AttributedString(nsAttributedString, including: \.uiKit)
    return Text(attributedString)
        .multilineTextAlignment(.center)
}
Platino answered 26/3, 2023 at 12:38 Comment(1)
You don't need to use NSAttributedString to create an AttributedString.Extravascular
W
1

Use UIViewRepresentable to get the UIKit Label

import Foundation
import UIKit
import SwiftUI


struct AttributedLabel: UIViewRepresentable {
    
    var attributedText: NSAttributedString
    
    func makeUIView(context: Context) -> UILabel {
        let label = UILabel()
        label.numberOfLines = 0
        label.attributedText = attributedText
        label.textAlignment = .left
        
        return label
    }
    
    func updateUIView(_ uiView: UILabel, context: Context) {
        uiView.attributedText = attributedText
    }
    
}

To use you just need to do this:

ZStack {
            AttributedLabel(attributedText: text)
    }
Winy answered 26/4, 2023 at 7:25 Comment(0)
P
0

Before iOS15, this support one style of markdown (font) text:

struct SingleMarkText: View {
    let text: String
    let mark: String
    let regularFont: Font
    let markFont: Font

    var body: some View {
        let array = text.components(separatedBy: mark)

        Group {
            array.enumerated()
                .reduce(Text("")) {
                    $0 + ($1.0 % 2 == 1 ? Text($1.1).font(markFont) : Text($1.1).font(regularFont))
                }
        }
    }
}

Usage:

SingleMarkText(
   text: "Hello __there__, how __are__ you?",
   mark: "__",
   regularFont: .body,
   markFont: .headline
)
.multilineTextAlignment(.center)
.foregroundColor(.black)
Pickled answered 13/7, 2023 at 3:14 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.