Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Attributed String in SwiftUI

Tags:

swift

swiftui

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

like image 309
Dattatray Deokar Avatar asked Dec 30 '19 12:12

Dattatray Deokar


People also ask

What is attributed string in Swift?

A value type for a string with associated attributes for portions of its text.

How do I make string bold in Swift?

let label = UILabel() label. attributedText = NSMutableAttributedString() . bold("Address: ") .


1 Answers

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")     } } 
like image 196
Mojtaba Hosseini Avatar answered Sep 20 '22 16:09

Mojtaba Hosseini