實(shí)用的簡(jiǎn)單富文本--UITextView實(shí)現(xiàn)恬涧,僅供參考焕刮,歡迎學(xué)習(xí)交流舶沿。
在登錄頁(yè),經(jīng)撑洳ⅲ看到這樣的字眼“xxx即表示同意AAAA和BBBB
”括荡,這里記錄一下簡(jiǎn)單的實(shí)現(xiàn)方式,僅供參考溉旋。
直接上代碼
當(dāng)然需要先遵守UITextView的協(xié)議:
<UITextViewDelegate>
@property (nonatomic, strong) UITextView *userProtocolAndPrivacyTextView;
[self.view addSubview:self.userProtocolAndPrivacyTextView];
- (UITextView *)userProtocolAndPrivacyTextView {
if (!_userProtocolAndPrivacyTextView) {
_userProtocolAndPrivacyTextView = [[UITextView alloc] initWithFrame:CGRectMake(24, 100, [UIScreen mainScreen].bounds.size.width - 48, 30)];
_userProtocolAndPrivacyTextView.backgroundColor = [UIColor clearColor];
// _userProtocolAndPrivacyTextView.font = [UIFont regularPingFangFontOfSize:14];
// _userProtocolAndPrivacyTextView.textColor = [UIColor colorWithRed:165/255.0 green:165/255.0 blue:165/255.0 alpha:1.0];
_userProtocolAndPrivacyTextView.editable = NO;
_userProtocolAndPrivacyTextView.delegate = self;
_userProtocolAndPrivacyTextView.textContainer.lineFragmentPadding = 0.0;
_userProtocolAndPrivacyTextView.textContainerInset = UIEdgeInsetsMake(0, 0, 0, 0);
_userProtocolAndPrivacyTextView.linkTextAttributes = @{NSForegroundColorAttributeName:[UIColor colorWithRed:35/255.0 green:135/255.0 blue:230/255.0 alpha:1.0]};
NSString *preTips = [NSString stringWithFormat:@"xx即表示同意"];
NSString *userProtocol= [NSString stringWithFormat:@"AAAA"];
NSString *privacyPolicy = [NSString stringWithFormat:@"BBBB"];
NSString *string = [NSString stringWithFormat:@"%@%@和%@", preTips, userProtocol, privacyPolicy];
NSMutableAttributedString *privacy = [[NSMutableAttributedString alloc] initWithString:string attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:14], NSForegroundColorAttributeName:[UIColor colorWithRed:165/255.0 green:165/255.0 blue:165/255.0 alpha:1.0]}];
NSRange userProtocolRange = [string rangeOfString:userProtocol];
NSRange privacyPolicyRange = [string rangeOfString:privacyPolicy];
[privacy addAttribute:NSLinkAttributeName value:@"user://" range:userProtocolRange];
[privacy addAttribute:NSLinkAttributeName value:@"privacy://" range:privacyPolicyRange];
_userProtocolAndPrivacyTextView.attributedText = privacy;
}
return _userProtocolAndPrivacyTextView;
}
接下來(lái)畸冲,看效果圖:
點(diǎn)擊對(duì)應(yīng)的藍(lán)色文字就會(huì)觸發(fā)UITextView的代理方法,如下:
//MARK: -- UITextViewDelegate
- (BOOL)textView:(UITextView *)textView shouldInteractWithURL:(nonnull NSURL *)URL inRange:(NSRange)characterRange interaction:(UITextItemInteraction)interaction API_AVAILABLE(ios(10.0)) {
if ([URL.scheme isEqualToString:@"user"]) {
NSLog(@"AAAA");
} else if ([URL.scheme isEqualToString:@"privacy"]) {
NSLog(@"BBBB");
}
return YES;
}
參考鏈接:https://blog.csdn.net/ForeverMyheart/article/details/117411351