I have a UILabel which shows the String. I need to change the color of the particular texts in the UILabel and when clicking on those texts it should open two different links in a webview. How to achieve this: The following code i have written:
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:@"This is Yahoo and Google" attributes:nil];
[attributedString addAttribute: NSForegroundColorAttributeName
value: [UIColor redColor]
range: NSMakeRange(8,5)];
[attributedString addAttribute: NSFontAttributeName
value: [UIFont fontWithName:@"Helvetica" size:15]
range: NSMakeRange(8,5)];
[attributedString addAttribute: NSFontAttributeName
value: [UIFont fontWithName:@"Didot" size:24]
range: NSMakeRange(18,6)];
self.linkLabel.attributedText = attributedString;
}
Now i want when the user clicks on google it should open google.com and when the user taps Yahoo it should open yahoo.com. how is ti possible?
try to change to UITextView and it should use the following
let verbiage = links.text! // UITextView text
let attributes = NSMutableAttributedString(string: verbiage)
let googleRange = (verbiage as NSString).range(of: "Google")
let yahooRange = (verbiage as NSString).range(of: "Yahoo")
attributes.addAttribute(NSLinkAttributeName, value: "https://www.google.com", range: googleRange)
attributes.addAttribute(NSLinkAttributeName, value: "https://www.yahoo.com", range: yahooRange)
let linkAttributes: [String : Any] = [
NSForegroundColorAttributeName: UIColor.red,
NSUnderlineColorAttributeName: UIColor.clear,
NSUnderlineStyleAttributeName: NSUnderlineStyle.styleNone.rawValue]
links.linkTextAttributes = linkAttributes
links.attributedText = attributes
Do not forget set Scrolling Enabled to false and Editable to false in order to get UITextView similar to UILabel