The new Swift Attributed String looks really neat, but is there a way to use it in UIKit or is it SwiftUI only? UITextViews take an NSAttributedString for their content, so I didn't know if there was a way I was missing for converting the AttributedString into an NSAttributedString.
Accepted Reply
NSAttributedString is given a new initializer taking an AttributedString.
convenience init(_ attrStr: AttributedString)
You can easily convert an AttributedString to an NSAttributedString:
var astr = AttributedString("Hello, world!")
if let range = astr.range(of: "world") {
astr[range].font = .boldSystemFont(ofSize: 22)
}
label.attributedText = NSAttributedString(astr)
-
Oh, you're right! it wasn't showing up in my autocomplete so I thought maybe the two were incompatible
-
Hi. Quick question. How do you do the opposite? How do you convert NSAttributedString into AttributedString. For instance, in case you want to add more attributes to the text of a UITextView.
Replies
NSAttributedString is given a new initializer taking an AttributedString.
convenience init(_ attrStr: AttributedString)
You can easily convert an AttributedString to an NSAttributedString:
var astr = AttributedString("Hello, world!")
if let range = astr.range(of: "world") {
astr[range].font = .boldSystemFont(ofSize: 22)
}
label.attributedText = NSAttributedString(astr)
-
Oh, you're right! it wasn't showing up in my autocomplete so I thought maybe the two were incompatible
-
Hi. Quick question. How do you do the opposite? How do you convert NSAttributedString into AttributedString. For instance, in case you want to add more attributes to the text of a UITextView.
How do you convert
NSAttributedStringintoAttributedString.
Also using an initialiser:
let ns: NSAttributedString = … something …
let a = try AttributedString(ns, including: \.uiKit)
Share and Enjoy
—
Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"
-
Thanks! I found the solution after posting the message, but instead of a key path I was using the data type directly, as in AttributeScopes.UIKitAttributes.self. This is a better implementation.