Skip to content

Using the links with HTML attributed string #817

Description

@devgokhan

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Fields

    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions