iOS UITextView 实现点击链接查看隐私政策和用户协议
///'#import ///'<UIKit/UIKit.h>///'//n//n@interface ViewController : UIViewController//n//n@property (nonatomic, strong) UITextView *textView;//n//n- (void)openLink:(UITapGestureRecognizer *)gestureRecognizer;//n//n@end//n//n#import ///'ViewController.h///'//n//n@interface ViewController ()//n//n@end//n//n@implementation ViewController//n//n- (void)viewDidLoad {//n [super viewDidLoad];//n //n // 创建UITextView//n self.textView = [[UITextView alloc] initWithFrame:self.view.bounds];//n self.textView.editable = NO;//n [self.view addSubview:self.textView];//n //n // 设置隐私政策和用户协议文本//n NSString *privacyPolicyText = ///'隐私政策///';//n NSString *userAgreementText = ///'用户协议///';//n NSString *textViewText = [NSString stringWithFormat:///'点击以下链接查看隐私政策和用户协议://n//n%@、%@///', privacyPolicyText, userAgreementText];//n //n // 创建NSMutableAttributedString//n NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:textViewText];//n //n // 添加链接//n NSRange privacyPolicyRange = [textViewText rangeOfString:privacyPolicyText];//n NSRange userAgreementRange = [textViewText rangeOfString:userAgreementText];//n //n [attributedString addAttribute:NSLinkAttributeName value:///'privacyPolicy://///' range:privacyPolicyRange]; // privacyPolicy:// 是自定义的链接标识//n [attributedString addAttribute:NSLinkAttributeName value:///'userAgreement://///' range:userAgreementRange]; // userAgreement:// 是自定义的链接标识//n //n // 设置NSMutableAttributedString到UITextView//n self.textView.attributedText = attributedString;//n //n // 添加手势识别器//n UITapGestureRecognizer *tapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(openLink:)];//n [self.textView addGestureRecognizer:tapGestureRecognizer];//n}//n//n- (void)openLink:(UITapGestureRecognizer *)gestureRecognizer {//n UITextView *textView = (UITextView *)gestureRecognizer.view;//n CGPoint location = [gestureRecognizer locationInView:textView];//n //n // 获取点击位置的链接//n NSURL *url = [textView.attributedText attribute:NSLinkAttributeName atIndex:location.x];//n if (url) {//n // 处理链接点击事件//n if ([url.absoluteString isEqualToString:///'privacyPolicy://///']) {//n // 点击了隐私政策链接//n NSLog(@/'点击了隐私政策链接///');//n } else if ([url.absoluteString isEqualToString:///'userAgreement://///']) {//n // 点击了用户协议链接//n NSLog(@/'点击了用户协议链接///');//n }//n }//n}//n//n@end//n///
原文地址: http://www.cveoy.top/t/topic/p0AQ 著作权归作者所有。请勿转载和采集!