admin管理员组文章数量:1434824
I am using Xcode 16.1 and attempting to convert an NSAttributedString to an AttributedString but the compiler doesn't recognise the init:
Here's my code:
let ns = NSAttributedString(string: "Fred")
let s = AttributedString(ns)
The compiler gives the error: Cannot convert value of type 'NSAttributedString' to expected argument type 'NSCoder'. The correct initialiser doesn't appear in autocomplete.
It works OK in playground and a new project, so I'm guessing something must be wrong with my project. I've tried all the usual cleanup actions.
I am using Xcode 16.1 and attempting to convert an NSAttributedString to an AttributedString but the compiler doesn't recognise the init:
Here's my code:
let ns = NSAttributedString(string: "Fred")
let s = AttributedString(ns)
The compiler gives the error: Cannot convert value of type 'NSAttributedString' to expected argument type 'NSCoder'. The correct initialiser doesn't appear in autocomplete.
It works OK in playground and a new project, so I'm guessing something must be wrong with my project. I've tried all the usual cleanup actions.
Share Improve this question asked Nov 18, 2024 at 13:44 easiwritereasiwriter 931 silver badge9 bronze badges 1 |1 Answer
Reset to default 2Ensure you're using Swift 5.5 or newer, as AttributedString was introduced in Swift 5.5.
Extension Code
extension NSAttributedString {
func toAttributedString() -> AttributedString? {
return AttributedString(self)
}
}
Usage
struct ContentView: View {
var body: some View {
let nsAttributedString = NSAttributedString(string: "Hello, Xcode 16!", attributes: [
.foregroundColor: UIColor.red,
.font: UIFont.boldSystemFont(ofSize: 18)
])
if let attributedString = nsAttributedString.toAttributedString() {
Text(attributedString)
} else {
Text("Failed to convert NSAttributedString")
}
}
}
本文标签: swiftuiHow to I convert NSAttributedString to AttributedStringStack Overflow
版权声明:本文标题:swiftui - How to I convert NSAttributedString to AttributedString - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745613524a2666258.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
iOS 15.0+
– Desdenova Commented Nov 18, 2024 at 14:41