Using `NSTextAttachment` in SwiftUI `Text`
Asked Answered
A

1

12

Does SwiftUI Text not work with NSTextAttachment? I have this AttributedString:

var attributedString: AttributedString {
    var sampleAttributedString = AttributedString(sampleText)
    // Apply some bold and italics attributes to sampleAttributedString
     ...
    // create NSMutableAttributedString
    let mutableAttributedString = NSMutableAttributedString(sampleAttributedString)
    let image1Attachment = NSTextAttachment()
    image1Attachment.image = UIImage(named: "audio.png")
    let imageString = NSAttributedString(attachment: image1Attachment)
    mutableAttributedString.append(imageString)
    mutableAttributedString.append(NSAttributedString(string: "End of text"))

    sampleAttributedString = AttributedString(mutableAttributedString)

    return sampleAttributedString
}

When I use the above in a SwiftUI view as follows:

var body: some View {
    Text(attributedString)
}

The image I embedded above does not show up. All the other text renders as expected. The catch isn't called. The image is in assets, I've tried with system images too.

The same logic works if I set the same attributed string to the attributedText property of a UILabel. Any help is appreciated.

Ankle answered 3/4, 2023 at 23:16 Comment(0)
J
0

I was researching how to do this in swiftUI too and I found this post

https://swiftuirecipes.com/blog/insert-image-into-swiftui-text

here is an example of how use it:

(Text("This image")
  + Text(Image("icon")) // HERE
  + Text("is our logo."))
    .font(.title)

hope this helps

Julesjuley answered 26/9, 2023 at 18:0 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.