2

i have a response coming in from the api in form of a text I want to scan that text for the word "Planned Parenthood health center" and insert a hyperlink on that word which redirects to plannedparenthood.org/health-center portal.

my approach:

NSString *text = response.content;
text = [text stringByReplacingOccurrencesOfString:@"Planned Parenthood health center" 
                                       withString:@"<a href=\"http://www.plannedparenthood.org/health-center\">Planned Parenthood health center</a>"];

though the link on the text is getting replaced. It is getting replaced by

<a href=\"http://www.plannedparenthood.org/health-center\">Planned Parenthood health center </a>

What's wrong why am I not getting any links there? am I doing something wrong I have also set the user enabled interaction to YES

highboi
  • 673
  • 7
  • 28
Ackman
  • 1,562
  • 6
  • 31
  • 54
  • `NSMutableAttributedString ` is your friend... – Fahim Parkar Dec 18 '16 at 08:15
  • Possible duplicate of [Create tap-able "links" in the NSAttributedText of a UILabel?](http://stackoverflow.com/questions/1256887/create-tap-able-links-in-the-nsattributedtext-of-a-uilabel) – highboi Jan 22 '17 at 20:00

1 Answers1

6

iOS does not handle this well to be honest probably because it intends you to use UIButtons which are much more easily tappable for users.

To accomplish what you want though, you cannot use a UILabel - you need to use a UITextView and set its attributedText property:

NSMutableAttributedString * attributedString = [[NSMutableAttributedString alloc] initWithString:@"Planned Parenthood health center"];
[attributedString addAttribute: NSLinkAttributeName value: @"http://www.plannedparenthood.com" range: NSMakeRange(0, str.length)];
textView.attributedText = attributedString;

Note that the UITextView must be selectable but not editable.

There is a bit of a downside with this method if you have other text in your attributed string that isn't linked. For example, if you have "Please select here in order to go to Planned Parenthood's website" where "here" is the only part of the text that you want linked. In this case, if you tap anywhere else in the text beside the word "here", you'll notice that it will be able to be selected by the user and have the blue highlight.

If using a UITextView is not desired, then you will need to use something custom such as TTTAttributedLabel

Josh Gafni
  • 2,831
  • 2
  • 19
  • 32