原理:
採用的是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
}