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
  • You need iOS 15.0+ – Desdenova Commented Nov 18, 2024 at 14:41
Add a comment  | 

1 Answer 1

Reset to default 2

Ensure 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