I've got some text coming from my server, some of which is HTML. I was able to use the attributed string and initWithData to format the text for display so that Apple shows as Apple and blue and underlined. But I couldn't detect the tap. I used TTTAttributedLabel and was able to write a dummy string and have it create a link whose tap I intercepted with didSelectLinkWithURL. Problem is, that method of defining the range of the text assumes you know the text of the link. I'm getting different strings each time, and I won't know what the string is to add the link to. Should I look for a tag opening and closing? Also, can TTT handle if the string has more than one link embedded in it?
Detecting links in html (with changing positions) in UILabel (TTTAttributedLabel)
823 views Asked by skinsfan00atg At
2
There are 2 answers
0
On
Here is the solution.. First setup your attributed text. Then find the links for each character. Then setup them with addLinkToUrl method.
NSAttributedString *attrString = [[NSAttributedString alloc] initWithData:
[text dataUsingEncoding:NSUTF8StringEncoding]
options:@{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType, NSCharacterEncodingDocumentAttribute: @(NSUTF8StringEncoding)}
documentAttributes:nil error:nil];
[label setAttributedText: attrString];
if (label.attributedText != nil && label.attributedText.length > 0) {
for (int i= 0; i < label.attributedText.length; i++) {
NSRange range = NSMakeRange(0,1);
NSDictionary<NSAttributedStringKey,id> *dict = [label.attributedText attributesAtIndex:i effectiveRange:&range];
if (dict[NSLinkAttributeName] != nil) {
NSURL *url = dict[NSLinkAttributeName];
[label addLinkToURL:url withRange:range];
}
}
}
After you do this you will be able to detect link taps with TTTAttributedLabelDelegate
- (void)attributedLabel:(TTTAttributedLabel *)label didSelectLinkWithURL:(NSURL *)url {
if([[UIApplication sharedApplication] canOpenURL:url]) {
[[UIApplication sharedApplication] openURL:url];
}
}
Display text in html code in UIWebview.
Load aboue text in the UIwebview