通常开发中,有时候会让我实现如下图所示的功能(一段文字上添加点击事件):
那我们怎么去实现呢?
直接上代码:
//内容文本
NSString *content = @"欢迎使用健康档案服务!为了让您放心使用产品及服务,请务必仔细阅读,充分理解协议中的条款内容后在点击同意,以便您更好的行使个人权利及保护个人隐私。\n\n注意:当你点击同意,即视为您已阅读并同意《健康档案服务协议》与《数字证书认证服务说明》。";
UITextView *contentTextView = [[UITextView alloc] initWithFrame:CGRectMake(12, 100, JnScreenWidth-24, 200)];
contentTextView.attributedText = [self getContentLabelAttributedText:content];
contentTextView.textAlignment = NSTextAlignmentLeft;
contentTextView.delegate = self;
contentTextView.editable = NO; //必须禁止输入,否则点击将弹出输入键盘
contentTextView.scrollEnabled = NO;
[self.view addSubview:contentTextView];
//----------------------------------
- (NSAttributedString *)getContentLabelAttributedText:(NSString *)text
{
NSMutableAttributedString *attrStr = [[NSMutableAttributedString alloc] initWithString:text attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:JnContentSize],NSForegroundColorAttributeName:[self colorWithHexString:@"#333333"]}];
[attrStr addAttribute:NSForegroundColorAttributeName value:[self colorWithHexString:@"#528DF0"] range:NSMakeRange(text.length-24, 10)];
[attrStr addAttribute:NSLinkAttributeName value:@"healthservice://" range:NSMakeRange(text.length-24, 10)];
[attrStr addAttribute:NSForegroundColorAttributeName value:[self colorWithHexString:@"#528DF0"] range:NSMakeRange(text.length-13, 12)];
[attrStr addAttribute:NSLinkAttributeName value:@"digitalcer://" range:NSMakeRange(text.length-13, 12)];
return attrStr;
}
接着,去实现UITextVIew的delegate就可以了
#pragma mark - UITextViewDelegate
- (BOOL)textView:(UITextView *)textView shouldInteractWithURL:(NSURL *)URL inRange:(NSRange)characterRange {
if ([[URL scheme] isEqualToString:@"healthservice"]) {
//《健康档案服务协议》点击事件
return NO;
}else if ([[URL scheme] isEqualToString:@"digitalcer"]) {
//《数字证书认证服务说明》点击事件
return NO;
}
return YES;
}
完了,是不是很简单!
Demo地址:https://github.com/JnKindle/AttributedString/tree/master
欢迎大家访问我的GitHub
GitTub:https://github.com/JnKindle