I have a requirement for iOS application where either using TextView or UILabel, show text which contains text and two links. If someone clicks on text link, that associated link has to open accordingly.
For eg: If you see the picture below there are two links. I could achieve this making text view text attributed and modifying text in Attributes Inspector.
Now My question is how to open links when user taps on virginia beach or niagara. How to identify which part of text was clicked by user ?
Links to be opened:
https://www.vbgov.com/Pages/default.aspx
https://www.niagarafallsusa.com/
I appreciate your help.
You can use NSMutableAttributedString to implement this functionality.
I've wrote a method which you can use, call this method from your viewDidLoad
- (void)configureLinks
{
NSString *fullString = @"Please accept the terms and conditions of virginia beach and Niagara.";
NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:fullString];
// Adding attributes
[attributedString addAttribute:NSLinkAttributeName value:@"https://www.vbgov.com/Pages/default.aspx" range:[fullString rangeOfString:@"virginia beach"]];
[attributedString addAttribute:NSLinkAttributeName value:@"https://www.niagarafallsusa.com/" range:[fullString rangeOfString:@"Niagara"]];
// For underline
[attributedString addAttribute:NSUnderlineStyleAttributeName value:@(NSUnderlineStyleSingle) range:[fullString rangeOfString:@"virginia beach"]];
[attributedString addAttribute:NSUnderlineStyleAttributeName value:@(NSUnderlineStyleSingle) range:[fullString rangeOfString:@"Niagara"]];
// Setting attributed string to textview
yourTextViewOrLabel.attributedText = attributedString;
}