Add pod 'NSAttributedStringBuilder13' to your Podfile.
SwiftUI Sample Project
Besides clearer NSAttributedString syntax, since NSAttributedStringBuilder uses Result Builder it also enables API to build components in UIViewRepresentable(which embeds UIView in a SwiftUI View).
Just like a SwiftUI Text takes a String as input, the purpose of AttributedText in the sample project is to take a NSAttributedString as input and render in SwiftUI.
To achieve this, AttributedText.swift uses @NSAttributedStringBuilder to support SwiftUI-style syntax:
Then using an AttributedText will be like:
Open the sample in /SwiftUISampleApp/AttributedTextSample.xcodeproj and check AttributedText. It uses UITextView, you can also use UILabel or NSTextView.
TODO
Better tests for image attachment
Known Issue
NSAttributedString does not support link color, therefore Link component with a .color() modifier has no effect. Alternatively you need to specify in UITextView.linkTextAttributes or .tintColor.
NSAttributedStringBuilder
Composing
NSAttributedStringwith SwiftUI-style syntax, powered by Result Builder.Project Link: https://github.com/ethanhuang13/NSAttributedStringBuilder
Features
NSAttributedString.KeyHow to use?
Traditionally we compose a
NSAttributedStringlike this:Now, with NSAttributedStringBuilder, we can use SwiftUI-like syntax to declare
NSAttributedString:Requirements
Xcode 12.5. This project uses Swift 5.4 feature Result Builder.
Installation
Swift Package
Open your project in Xcode 12, navigate to Menu -> Swift Packages -> Add Package Dependency and enter https://github.com/ethanhuang13/NSAttributedStringBuilder to install.
CocoaPods
Add
pod 'NSAttributedStringBuilder13'to yourPodfile.SwiftUI Sample Project
Besides clearer
NSAttributedStringsyntax, since NSAttributedStringBuilder uses Result Builder it also enables API to build components inUIViewRepresentable(which embedsUIViewin a SwiftUIView).Just like a SwiftUI
Texttakes aStringas input, the purpose ofAttributedTextin the sample project is to take aNSAttributedStringas input and render in SwiftUI.To achieve this,
AttributedText.swiftuses@NSAttributedStringBuilderto support SwiftUI-style syntax:Then using an
AttributedTextwill be like:Open the sample in /SwiftUISampleApp/AttributedTextSample.xcodeproj and check
AttributedText. It usesUITextView, you can also useUILabelorNSTextView.TODO
Known Issue
NSAttributedStringdoes not support link color, thereforeLinkcomponent with a.color()modifier has no effect. Alternatively you need to specify inUITextView.linkTextAttributesor.tintColor.Others
Initially discussed on this Twitter thread. Some code are inspired by zonble🙏.