1

I found that there are two ways to create an NSTextAttachment of an image:

// Way 1:
let attachment = NSTextAttachment()
attachment.image = UIImage(named: "...")

// Way 2:
let attachment = NSTextAttachment(image: UIImage(named: "...")!)

I thought these two ways are totally the same, until I did it with SF Symbols' images:

let imageAttachment = NSTextAttachment()
imageAttachment.image = UIImage(systemName: "photo")!

let fullString = NSMutableAttributedString(string: "1: Press the ")
fullString.append(NSAttributedString(attachment: imageAttachment))
fullString.append(NSAttributedString(string: " button"))
textview.attributedText = fullString

produces:

enter image description here

whereas:

let imageAttachment = NSTextAttachment(image: UIImage(systemName: "photo")!)

let fullString = NSMutableAttributedString(string: "1: Press the ")
fullString.append(NSAttributedString(attachment: imageAttachment))
fullString.append(NSAttributedString(string: " button"))
textview.attributedText = fullString

produces:

enter image description here

I thought maybe way 2 "preserves colours" or something like that, but if I use my own image, both ways produce the same result.

Both of their documentations (1, 2) don't say anything about how they are different. Both seems to say the same thing...

So what does NSTextAttachment(image:) do, that .image = ... doesn't? Or, what does .image = ... do, that NSTextAttachment(image:) doesn't? Are there other images (other than SF symbol images) that I can see a difference?

I'm running this on Xcode 11.0 and iOS 13.0, so it might be a bug of a non-latest version of iOS?

Sweeper
  • 213,210
  • 22
  • 193
  • 313
  • I just checked thi on Xcode 11.3 and iOS 13.3 and it gives me the same results as way 1. It must be a bug in iOS 13.0 – BhargavR Apr 16 '20 at 11:32
  • @BhargavR Hmm... I ran the binary compiled with Xcode 11.0 on my iOS 13.3.1 phone and I still see the blue image. Probably an Xcode thing then. At least now I know people won't see different things on different iOS versions. – Sweeper Apr 16 '20 at 12:02
  • Interesting, maybe there https://stackoverflow.com/questions/29041458/how-to-set-color-of-templated-image-in-nstextattachment ? – Larme Apr 16 '20 at 14:26
  • @Larme That question does indeed seem to be somewhat related... Another discovery I made was that the blue color produced by Way 2 actually comes from `tintColor` of the text view. If I change the tint color to red, then Way 2 produces a red image. I feel like `.alwaysTemplated` is probably one closer to the answer, but still doesn't explain why it doesn't do it to non SF symbols images. – Sweeper Apr 16 '20 at 14:37

0 Answers0