-4

I have the following NSString:

NSString *example = @" I like cheese and ham and eggs, but ham more than cheese and cheese more than ham!";

I'd like to change this into an NSAttributable string so that I can output this in a UITextView where cheese becomes a hyperlink to www.cheese.com and ham becomes a hyperlink to www.ham.com

Is this at all possible?

Matt

user1419810
  • 836
  • 1
  • 16
  • 29
  • Why so many related questions? – Larme Oct 15 '15 at 14:22
  • Possible duplicate of [How do I convert an NSString value to NSData?](http://stackoverflow.com/questions/901357/how-do-i-convert-an-nsstring-value-to-nsdata) – maxshuty Oct 15 '15 at 14:24
  • 3
    @MaxPoshusta That's not even close to this question. – rmaddy Oct 15 '15 at 14:25
  • In case you're using `UITextView` because you thought that was the only way to do it, I thought I should mention it's possible to do this with a [UILabel](http://stackoverflow.com/a/29352519/168594). – zekel Oct 15 '15 at 14:56

1 Answers1

0

Use the following code. I have just manually calculated the range for the string. But you can make it automated. Its just a example.

NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:@"I like cheese and ham and eggs, but ham more than cheese and cheese more than ham!"];
[str addAttribute:NSLinkAttributeName value:[NSURL URLWithString: @"http://www.cheese.com"] range: NSMakeRange(6, [@"cheese" length])];
tempTextView.attributedText = str;

And then use below delegate method to get action :

- (BOOL)textView:(UITextView *)textView shouldInteractWithURL:(NSURL *)url inRange:(NSRange)characterRange
Sneha
  • 1,444
  • 15
  • 24