iOS技术之TextView实现部分字符串赋予点击事件

文章讲述了如何在UITextFieldDelegate中设置TextView,包括禁止编辑、设置文本样式,以及处理用户点击链接的行为,区分链接到《服务协议》和《隐私政策》的不同操作。

1.遵守UITextFieldDelegate代理

- (UITextView *)textView {
    if (!_textView) {
        _textView = [[UITextView alloc] init];
        _textView.scrollEnabled = NO;
        _textView.editable = NO;
        _textView.textContainer.lineFragmentPadding = 0;
        _textView.textContainerInset = UIEdgeInsetsMake(0, 0, 0, 0);
        _textView.textColor =[UIColor blackColor];
        _textView.backgroundColor = [UIColor clearColor];
        
        NSString *string = @"我已阅读并同意《服务协议》和《隐私政策》";
        NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:string];
        [str addAttributes:@{NSForegroundColorAttributeName:[UIColor redColor]} range:[string rangeOfString:@"《服务协议》"]];
        

        NSDictionary *attr = [NSDictionary dictionaryWithObjectsAndKeys:
                              @"sProtocol", NSLinkAttributeName, nil];
        [str addAttributes:attr range:[string rangeOfString:@"《服务协议》"]];
        NSDictionary *attr1 = [NSDictionary dictionaryWithObjectsAndKeys:
                               @"pProtocol", NSLinkAttributeName, nil];
        [str addAttributes:@{NSForegroundColorAttributeName:[UIColor redColor]} range:[string rangeOfString:@"《隐私政策》"]];
        [str addAttributes:attr1 range:[string rangeOfString:@"《隐私政策》"]];
        _textView.attributedText = str;
        _textView.textAlignment = NSTextAlignmentLeft;
        _textView.font = kYP_System_FontSize(14);
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(actionTextView:)];
        [_textView addGestureRecognizer:tap];
        
    }
    return _textView;
}

- (void)actionTextView:(UIGestureRecognizer *)gestureRecognizer {
    QNLog(@"点击我已阅读协议");
    
    // 判断是否点击了超链接
    if ([gestureRecognizer.view isKindOfClass:[UITextView class]]) {
        UITextView *textView = (UITextView *)gestureRecognizer.view;
        CGPoint tapLocation = [gestureRecognizer locationInView:textView];
        UITextPosition *tapPosition = [textView closestPositionToPoint:tapLocation];
        
        NSDictionary *attributes = [textView textStylingAtPosition:tapPosition inDirection:UITextStorageDirectionBackward];

        NSString *url = attributes[NSLinkAttributeName];
        if (!url) {
            
            // 如果点击了超链接,则不识别自定义点击手势
            if ([url isEqualToString:@"sProtocol"]) {
                NSLog(@"sProtocol");
            } else if ([url isEqualToString:@"pProtocol"]) {
                NSLog(@"pProtocol");
            }
        } else {
            NSLog(@"点击其他");
        }
        
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值