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(@"点击其他");
}
}
}
文章讲述了如何在UITextFieldDelegate中设置TextView,包括禁止编辑、设置文本样式,以及处理用户点击链接的行为,区分链接到《服务协议》和《隐私政策》的不同操作。
4403

被折叠的 条评论
为什么被折叠?



