Swiftpack.co is a collection of thousands of indexed Swift packages. Search packages.
AttributedText
AttributedText is a Swift µpackage that provides NSAttributedString
rendering in SwiftUI by wrapping either an NSTextView
or a UITextView
depending on the platform.
Supported Platforms
- macOS 11.0+
- iOS 14.0+
- tvOS 14.0+
Usage
import AttributedText
struct ContentView: View {
private let attributedString: NSAttributedString = {
let result = NSMutableAttributedString(
string: """
After the Big Bang
A brief summary of time
Life on earth
10 billion years
You reading this
13.7 billion years
"""
)
result.addAttributes([.font: UIFont.preferredFont(forTextStyle: .title1)], range: NSRange(location: 0, length: 18))
result.addAttributes([.link: URL(string: "https://en.wikipedia.org/wiki/Big_Bang")!], range: NSRange(location: 10, length: 8))
result.addAttributes([.font: UIFont.preferredFont(forTextStyle: .body)], range: NSRange(location: 19, length: 23))
result.addAttributes([.font: UIFont.preferredFont(forTextStyle: .title2)], range: NSRange(location: 43, length: 13))
result.addAttributes([.font: UIFont.preferredFont(forTextStyle: .body)], range: NSRange(location: 57, length: 16))
result.addAttributes([.font: UIFont.preferredFont(forTextStyle: .title2)], range: NSRange(location: 74, length: 16))
result.addAttributes([.font: UIFont.preferredFont(forTextStyle: .body)], range: NSRange(location: 91, length: 18))
return result
}()
var body: some View {
AttributedText(attributedString)
.background(Color.gray.opacity(0.5))
.accentColor(.purple)
}
}
An AttributedText
view takes all the available width and adjusts its height to fit the contents.
To change the text alignment or line break mode, you need to add a .paragraphStyle
attribute to the attributed string.
Installation
You can add AttributedText to an Xcode project by adding it as a package dependency.
- From the File menu, select Swift Packages › Add Package Dependency…
- Enter
https://github.com/gonzalezreal/AttributedText
into the package repository URL text field - Link AttributedText to your application target
Github
link |
Stars: 13 |
Related Packages
You may find interesting
Releases
AttributedText 0.2.1 - 2021-01-08T08:11:30
- Fix macOS resize issue
- More simple layout strategy
AttributedText 0.2.0 - 2021-01-03T15:34:17
- Refactor the view layout using a store shared between the main view and the native view wrapper. Now the height of the view is updated during the layout phase. This has positive side-effects like proper previews and faster updates. On top of that, we can now do proper snapshot testing.
AttributedText 0.1.6 - 2020-12-26T09:44:50
- Consider line limit and truncation mode environment values
AttributedText 0.1.4 - 2020-12-21T14:25:19
- Allow animated updates
AttributedText 0.1.3 - 2020-12-20T14:08:49
- Fix watchOS builds
AttributedText 0.1.2 - 2020-12-20T10:26:21
- Resize image attachments to fit the view
AttributedText 0.1.1 - 2020-12-18T23:06:54
- Add license