iOS - 富文本指定文字点击实现(仿超链接)

iOS - 富文本指定文字点击实现(仿超链接)_第1张图片

就这种。

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {

    [super viewDidLoad];

    // Do any additional setup after loading the view, typically from a nib.

    NSString *str1 = @"大美女";

    NSString *str2 = @"爱上了英俊的";

    NSString *str3 = @"xtayqria";

    NSString *str = [NSString stringWithFormat:@"%@%@%@",str1,str2,str3];

    

    NSRange range1 = [str rangeOfString:str1];

    NSRange range2 = [str rangeOfString:str2];

    NSRange range3 = [str rangeOfString:str3];

    

    UITextView *textView = [[UITextView alloc] init];

    textView.frame = CGRectMake(40, 100, 300, 50);

    textView.editable = NO;

    textView.delegate = self;

    [self.view addSubview:textView];

    

    NSMutableAttributedString *mastring = [[NSMutableAttributedString alloc] initWithString:str attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:22.0f]}];

    [mastring addAttribute:NSForegroundColorAttributeName value:[UIColor greenColor] range:range1];

    [mastring addAttribute:NSForegroundColorAttributeName value:[UIColor blackColor] range:range2];

    [mastring addAttribute:NSForegroundColorAttributeName value:[UIColor greenColor] range:range3];

    // 1.必须要用前缀(firstPerson,secondPerson),随便写但是要有

    // 2.要有后面的方法,如果含有中文,url会无效,所以转码

    NSString *valueString1 = [[NSString stringWithFormat:@"firstPerson://%@",str1] stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLFragmentAllowedCharacterSet]];

    NSString *valueString3 = [[NSString stringWithFormat:@"secondPerson://%@",str3] stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLFragmentAllowedCharacterSet]];

    

    [mastring addAttribute:NSLinkAttributeName value:valueString1 range:range1];

    [mastring addAttribute:NSLinkAttributeName value:valueString3 range:range3];

    

    textView.attributedText = mastring;

}

- (BOOL)textView:(UITextView *)textView shouldInteractWithURL:(NSURL *)URL inRange:(NSRange)characterRange {

    if ([[URL scheme] isEqualToString:@"firstPerson"]) {

        NSString *titleString = [NSString stringWithFormat:@"你点击了第一个文字:%@",[URL host]];

        [self clickLinkTitle:titleString];

        return NO;

    } else if ([[URL scheme] isEqualToString:@"secondPerson"]) {

        NSString *titleString = [NSString stringWithFormat:@"你点击了第二个文字:%@",[URL host]];

        [self clickLinkTitle:titleString];

        return NO;

    }

    return YES;

}

- (void)clickLinkTitle:(NSString *)title {

    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:title preferredStyle:UIAlertControllerStyleAlert];

    UIAlertAction *action = [UIAlertAction actionWithTitle:@"好的" style:UIAlertActionStyleCancel handler:nil];

    [alert addAction:action];

    [self presentViewController:alert animated:YES completion:nil];

}

// ---------------图片--------------------//

你可能感兴趣的:(iOS基础)