点击富文本部分文字跳转功能。
通常用在统一用户协议,隐私协议,儿童协议,移动认证服务条款。
注意实现:由于采用UITextView实现,一行显示没有问题,但是当需要多行显示时,由于他有行间距和头部空白取,不会像UILabel定格显示,需要适当增加高度来显示多行,高度设置小了只显示一行,不会换行。需要适当向上微移来进行对齐其它UI元素。
网上那种只在UILabel添加手势事件的方式,显示无法控制点击指定部分文字跳转,多UILabel的方式也不能处理换行的情况。一般的协议大都有多个,那种方案显然无法实现。我这种方案才是最终实现方案。
具体代码:
1.设置协议:
@interface QYLoginPanel ()<UITextViewDelegate>
2.增加UITextView对象和添加富文本,这个是核心:
- (UITextView *)textView {
if (!_textView) {
_textView = [[UITextView alloc]init];
_textView.backgroundColor = UIColor.clearColor;
_textView.textColor = RGBA(255, 255, 255, 0.6);
_textView.font = [UIFont systemFontOfSize:12];
NSString *str = @"注册即表示同意《用户隐私》《隐私协议》以及《移动认证服务条款》";
NSMutableAttributedString *att = [[NSMutableAttributedString alloc] initWithString:str];
[att addAttribute:NSLinkAttributeName value:@"privacyPolicy://" range:NSMakeRange(14, 4)];
[att addAttribute:NSLinkAttributeName value:@"userProtocol://" range:NSMakeRange(8, 5)];
[att addAttribute:NSLinkAttributeName value:@"mobileProtocol://" range:NSMakeRange(22, 8)];
[att addAttribute:NSForegroundColorAttributeName value:RGBA(255, 255, 255, 0.6) range:NSMakeRange(0, str.length)];
// [att addAttribute:NSForegroundColorAttributeName value:RGBA(255, 255, 255, 1.0) range:NSMakeRange(8, 4)];
// [att addAttribute:NSForegroundColorAttributeName value:RGBA(255, 255, 255, 1.0) range:NSMakeRange(14, 4)];
// [att addAttribute:NSForegroundColorAttributeName value:RGBA(255, 255, 255, 1.0) range:NSMakeRange(22, 8)];
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
paragraphStyle.paragraphSpacing = QY_1PX;
paragraphStyle.lineSpacing = QY_1PX;
paragraphStyle.minimumLineHeight = 14;
paragraphStyle.paragraphSpacingBefore = QY_1PX;
[att addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, str.length)];
_textView.linkTextAttributes = @{NSForegroundColorAttributeName: RGBA(255, 255, 255, 1.0)};
_textView.delegate = self;
_textView.editable = NO; //必须禁止输入,否则点击将弹出输入键盘
_textView.scrollEnabled = NO;
_textView.attributedText = att;
// _textView.userInteractionEnabled = YES;
_textView.font = [UIFont systemFontOfSize:12];
_textView.textAlignment = NSTextAlignmentLeft;
}
return _textView;
}
3.添加点击回调事件:
#pragma mark - UITextViewDelegate
- (BOOL)textView:(UITextView *)textView shouldInteractWithURL:(NSURL *)URL inRange:(NSRange)characterRange {
if ([[URL scheme] isEqualToString:@"privacyPolicy"]) {
//《隐私政策》
NSLog(@"点击了《隐私政策》");
return NO;
}else if ([[URL scheme] isEqualToString:@"userProtocol"]) {
//《用户隐私》
NSLog(@"点击了《用户隐私》");
return NO;
}else if ([[URL scheme] isEqualToString:@"mobileProtocol"]) {
//《移动认证服务条款》
NSLog(@"点击了《移动认证服务条款》");
return NO;
}
return YES;
}