简体   繁体   中英

Make a clickable link in an NSAttributedString for a UITextView

I made a clickable link. My code:

NSString *textBlah = @"blah bleh bluh blih....";

    - (void)hyperLinkAndColor:(NSString*)name withAttribute:(NSMutableAttributedString*)attributedText{

        if ([textBlah rangeOfString:name].location != NSNotFound) {
            NSRange rangeName = [textInformation rangeOfString:name];
            if ([name rangeOfString:@" "].location != NSNotFound) {
                name = [name stringByReplacingOccurrencesOfString:@" " withString:@"%20"];
            }

            NSURL* url = [NSURL URLWithString:[NSString stringWithFormat:@"linktink://?name=%@", name]];
            [attributedText beginEditing];
            [attributedText addAttribute:NSLinkAttributeName value:[url absoluteString] range:rangeName];
            [attributedText addAttribute:NSForegroundColorAttributeName value:[UIColor orangeColor] range:rangeName];
            [attributedText endEditing];
        }
    }        

It works fine. But i get one issue. When 'name' is 您好 or হ্যালো or héllò..., url always return nil.How to detect 您好 or হ্যালো ... and make clickable on it?

Modify the code to URL Encode the string so that unicode characters won't create an issue.

NSString *textBlah = @"blah bleh bluh blih....";

- (void)hyperLinkAndColor:(NSString*)name withAttribute:(NSMutableAttributedString*)attributedText{

    if ([textBlah rangeOfString:name].location != NSNotFound) {

        NSRange rangeName = [textInformation rangeOfString:name];
        NSString *urlString = [NSString stringWithFormat:@"linktink://?name=%@", name];

        NSURL* url = [NSURL URLWithString:[urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
        [attributedText beginEditing];
        [attributedText addAttribute:NSLinkAttributeName value:[url absoluteString] range:rangeName];
        [attributedText addAttribute:NSForegroundColorAttributeName value:[UIColor orangeColor] range:rangeName];
        [attributedText endEditing];
    }
}        

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM