最新消息:Welcome to the puzzle paradise for programmers! Here, a well-designed puzzle awaits you. From code logic puzzles to algorithmic challenges, each level is closely centered on the programmer's expertise and skills. Whether you're a novice programmer or an experienced tech guru, you'll find your own challenges on this site. In the process of solving puzzles, you can not only exercise your thinking skills, but also deepen your understanding and application of programming knowledge. Come to start this puzzle journey full of wisdom and challenges, with many programmers to compete with each other and show your programming wisdom! Translated with DeepL.com (free version)

swiftui - How to I convert NSAttributedString to AttributedString - Stack Overflow

matteradmin10PV0评论

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")
        }
    }
}   
Post a comment

comment list (0)

  1. No comments so far