0

I have an NSTextAttachment with an image in a UILabel and I would like to perform a custom behaviour when clicking on this attachment.

UITextViewDelegate provides an handy method

textView:shouldInteractWithTextAttachment:inRange:

But it can only be used if I'm using UITextView.

Is there any solution if Im using UILabel?

Thanks!

Sam Fischer
  • 1,442
  • 19
  • 35
ram
  • 21
  • 4

1 Answers1

2

The text attachment becomes part of the model and is treated like a character, so try adding a link to the range of your attachment. Like this:

NSTextAttachment *attachment = [[NSTextAttachment alloc] initWithData:nil ofType:nil];
attachment.image = [UIImage imageNamed:@"myImage"];

NSAttributedString *imageString = [NSAttributedString attributedStringWithAttachment:attachment];
NSMutableAttributedString *mutableImageString = [imageString mutableCopy];
[mutableImageString addAttribute:NSLinkAttributeName value:@"http://stackoverflow.com" range:NSMakeRange(0, mutableImageString.length)];
Andrew
  • 3,166
  • 21
  • 32