iOS 如何给将超链接转换成指定文字

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    UITextView *textView = [[UITextView alloc] initWithFrame:CGRectMake(100, 500, 200, 200)];
    [self.view addSubview:textView];
    textView.dataDetectorTypes = UIDataDetectorTypeLink;
    textView.delegate = self;
    [textView setSelectable: YES];
    //非编辑状态下,才能允许跳转
    [textView setEditable:NO];

    NSString *str = @"这里的天气很好https://www.baidu.com我要到百度上面去买个面膜https://www.iconfont.cn这里的天气很好http://www.cocoachina.com我要到百度上面去买个面膜https://c.y.qq.com/base/fcgi-bin/u?__=9Is2JD2";
    NSURL *url = [NSURL URLWithString:@"http:www.baidu.com"];
    NSLog(@"%@", url.standardizedURL);
    
    NSMutableAttributedString *attributedString = [self changeUrlTo:str];
    textView.linkTextAttributes = @{NSForegroundColorAttributeName: [UIColor redColor], NSUnderlineColorAttributeName: [UIColor lightGrayColor], NSUnderlineStyleAttributeName: @(NSUnderlinePatternSolid)};
    textView.attributedText = attributedString;
    
}

/**
  代理方法
 */
- (BOOL)textView:(UITextView *)textView shouldInteractWithURL:(NSURL *)URL inRange:(NSRange)characterRange {
    NSLog(@"URL = %@", URL);
    NSString *url = [NSString stringWithFormat:@"%@",URL];
    NSLog(@"url = %@", url);
    [[UIApplication sharedApplication]openURL:[NSURL URLWithString:url] options:@{} completionHandler:^(BOOL success) {
    }];
    return YES;
}


- (NSMutableAttributedString *)changeUrlTo:(NSString *)str{
    // 1, 截取http字段
    NSArray *allUrlArray = [self getURLFromStr:str];
    NSLog(@"allUrlArray = %@", allUrlArray);
    for (NSString *s in allUrlArray) {
        if ([str containsString:s]) {
            NSLog(@"%@", s);
            str = [str stringByReplacingOccurrencesOfString:s withString:@"* @超链接 "];
        }
    }
    NSArray *locArray =  [self getRangeStr:str findText:@"* @"];
    NSLog(@"locArray = %@", locArray);

    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:str];
    

    NSTextAttachment *attach = [[NSTextAttachment alloc] init];
    attach.image =[UIImage imageNamed:@"chaolianjie.png"]; //设置图片
    attach.bounds = CGRectMake(0, -3, 13, 13); //设置图片大小、位置

    for (int i = 0; i < allUrlArray.count; i++) {
        NSInteger loc = [locArray[i] integerValue];
        NSAttributedString *str2 = [NSAttributedString attributedStringWithAttachment:attach];
        [attributedString replaceCharactersInRange:NSMakeRange(loc, 1) withAttributedString:str2];
    }

    for (int i = 0; i < allUrlArray.count; i++) {
        NSInteger loc = [locArray[i] integerValue];
        NSRange rang = NSMakeRange(loc, 7);
        NSLog(@"%@", NSStringFromRange(rang));
        NSString *url = allUrlArray[i];
        NSString *value = [NSString stringWithFormat:@"%@",url];
        NSLog(@"value = %@", value);
        [attributedString addAttribute:NSLinkAttributeName value:value range:rang];
    }
    return attributedString;
}

- (NSArray*)getURLFromStr:(NSString *)string {
    NSError *error;
    //可以识别url的正则表达式
    NSString *regulaStr = @"((http[s]{0,1}|ftp)://[a-zA-Z0-9\\.\\-]+\\.([a-zA-Z]{2,4})(:\\d+)?(/[a-zA-Z0-9\\.\\-~!@#$%^&*+?:_/=<>]*)?)|(www.[a-zA-Z0-9\\.\\-]+\\.([a-zA-Z]{2,4})(:\\d+)?(/[a-zA-Z0-9\\.\\-~!@#$%^&*+?:_/=<>]*)?)";
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:regulaStr options:NSRegularExpressionCaseInsensitive error:&error];
    NSArray *arrayOfAllMatches = [regex matchesInString:string options:0 range:NSMakeRange(0, [string length])];\
    NSLog(@"arrayOfAllMatches = %@", arrayOfAllMatches);
    NSMutableArray *arr=[[NSMutableArray alloc] init];
    for (NSTextCheckingResult *match in arrayOfAllMatches){
        NSString* substringForMatch;
        substringForMatch = [string substringWithRange:match.range];
        NSLog(@"match = %@", substringForMatch);
        NSLog(@"substringForMatch = %@", substringForMatch);
        [arr addObject:substringForMatch];
    }
    return arr;
}

- (NSMutableArray *)getRangeStr:(NSString *)text findText:(NSString *)findText{
    NSMutableArray *arrayRanges = [NSMutableArray arrayWithCapacity:3];
    if (findText == nil && [findText isEqualToString:@""]){
        return nil;
    }
    NSRange rang = [text rangeOfString:findText]; //获取第一次出现的range
    if (rang.location != NSNotFound && rang.length != 0){
        [arrayRanges addObject:[NSNumber numberWithInteger:rang.location]];//将第一次的加入到数组中
        NSRange rang1 = {0,0};
        NSInteger location = 0;
        NSInteger length = 0;
        for (int i = 0;; i++){
            if (0 == i){//去掉这个xxx
                location = rang.location + rang.length;
                length = text.length - rang.location - rang.length;
                rang1 = NSMakeRange(location, length);
            }else{
                location = rang1.location + rang1.length;
                length = text.length - rang1.location - rang1.length;
                rang1 = NSMakeRange(location, length);
            }
            //在一个range范围内查找另一个字符串的range
            rang1 = [text rangeOfString:findText options:NSCaseInsensitiveSearch range:rang1];
            if(rang1.location == NSNotFound && rang1.length == 0){
                break;
            }else//添加符合条件的location进数组
                [arrayRanges addObject:[NSNumber numberWithInteger:rang1.location]];
        }
        return arrayRanges;
    }
    return nil;
}

@end

你可能感兴趣的:(iOS 如何给将超链接转换成指定文字)