原理:
采用的是UITextView的URL链接,设置UITextView.attributedText并设置代理delegate,响应的回调函数shouldInteractWithURL。
实现:
//使用textView的URL链接
UITextView *protocolTextView = [[UITextView alloc] init]
[_mainScrollView addSubview:protocolTextView]
protocolTextView.backgroundColor = [UIColor clearColor]
protocolTextView.delegate = self
protocolTextView.editable = NO
protocolTextView.scrollEnabled = NO
NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc]initWithString:@"我已经同意遵守阅读《中国水泥备件网服务协议》"]
[attributedString addAttribute:NSLinkAttributeName
value:@"protocol://"
range:[[attributedString string] rangeOfString:@"《中国水泥备件网服务协议》"]]
protocolTextView.attributedText = attributedString
protocolTextView.linkTextAttributes = @{ NSForegroundColorAttributeName: [UIColor blueColor],
NSUnderlineColorAttributeName: [UIColor clearColor],
NSUnderlineStyleAttributeName: @(NSUnderlineStyleSingle)}
[protocolTextView mas_makeConstraints:^(MASConstraintMaker *make) {
make.top.equalTo(confirmPasswordLabel.mas_bottom).offset(30)
make.width.mas_equalTo(280)
make.height.mas_equalTo(30)
make.centerX.equalTo(_mainScrollView.mas_centerX).offset(20)
}]
#pragma mark - UITextViewDelegate
- (BOOL)textView:(UITextView *)textView shouldInteractWithURL:(NSURL *)URL inRange:(NSRange)characterRange {
if ([[URL scheme] isEqualToString:@"protocol"]) {
RegistrationProtocolViewController *vc = [[RegistrationProtocolViewController alloc] init]
vc.urlString = @"http://192.168.1.203:8888/Home/Login/apiDeclare"
[self.navigationController pushViewController:vc animated:YES]
}
return YES
}