iOS adds click event to text through TextView rich text

UITextView *protocolTV = [[UITextView alloc]initWithFrame:CGRectMake(50,200, 200, 100)];

//    protocolTV.frame = CGRectMake(15, 15, SCREEN_WIDTH - 30, 40);

    protocolTV.editable = NO;

    protocolTV.delegate = self;

    protocolTV.textContainer.lineFragmentPadding = 0.0;

    protocolTV.textContainerInset = UIEdgeInsetsMake(15, 0, 0, 0);

    protocolTV.linkTextAttributes = @{NSForegroundColorAttributeName:[UIColor blueColor]};

    [self.view addSubview:protocolTV];

    NSString *appName = [NSBundle mainBundle].infoDictionary[@"CFBundleDisplayName"];

    NSString *rangeStr = [NSString stringWithFormat:@"This is the "%@Privacy Policy" we want to follow", appName];

    NSString *protocolStr = [NSString stringWithFormat:@"read and agree%@",rangeStr];

    NSString *serverce= [NSString stringWithFormat:@""Service Agreement""];

    NSRange privacyRange = [protocolStr rangeOfString:rangeStr];

    NSString *preStr = [NSString stringWithFormat:@"This is what we want to follow"];

    NSMutableAttributedString *privacy = [[NSMutableAttributedString alloc]initWithString:[NSString stringWithFormat:@"%@%@",preStr,protocolStr] attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:20],NSForegroundColorAttributeName:[UIColor blueColor]}];

    NSRange range = [rangeStr rangeOfString:preStr];

    [privacy setAttributes:@{NSForegroundColorAttributeName:[UIColor blackColor],NSFontAttributeName:[UIFont systemFontOfSize:20]} range:[rangeStr rangeOfString:preStr]];

    [privacy addAttribute:NSLinkAttributeName value:@"privacy://" range:privacyRange];

   

   

    NSMutableAttributedString *servercePrivacy = [[NSMutableAttributedString alloc]initWithString:serverce attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:20.0],NSForegroundColorAttributeName:[UIColor blueColor]}];

    NSRange serverceRange = [serverce rangeOfString:serverce];

    [servercePrivacy addAttribute:NSLinkAttributeName value:@"serverce://" range:serverceRange];

    [privacy appendAttributedString:servercePrivacy];

    protocolTV.attributedText = privacy;

    [self.view addSubview:protocolTV];

 

 

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

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

        NSLog(@"clicked the privacy agreement");

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

        NSLog(@"clicked the service agreement");

    }

    return YES;

}

Guess you like

Origin blog.csdn.net/ForeverMyheart/article/details/117411351
Recommended