Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Using the links with HTML attributed string #817

Open
devgokhan opened this issue Mar 22, 2021 · 0 comments
Open

Using the links with HTML attributed string #817

devgokhan opened this issue Mar 22, 2021 · 0 comments

Comments

@devgokhan
Copy link

devgokhan commented Mar 22, 2021

Maybe you can add this feature.. Or anybody needs this, can use this..

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];
    } 
}

I also shared this solution in one of the stackoverflow question:
https://stackoverflow.com/questions/30872730/detecting-links-in-html-with-changing-positions-in-uilabel-tttattributedlabel/66747280#66747280

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant