UITextView打开文字中的URL

时间:2023-03-09 00:37:10
UITextView打开文字中的URL

1. 背景介绍

UITextView里显示的文字带有url,点击url可以打开对应的网页,可以分两种打开方式:(1)在App内打开url;(2)用safari打开url。

2. 实现代码:

(1)声明并add  UITextView

// 声明UITextView

    @property(nonatomic, strong)UITextView *quesDescText;

//设置并 add UITextView

    self.quesDescText = [[UITextView alloc] init];
    self.quesDescText.text = self.quesDesc;
    self.quesDescText.size = [self quesDescLabelSize];
    self.quesDescText.font = font;
    self.quesDescText.scrollEnabled = NO;
    self.quesDescText.editable = NO;
    self.quesDescText.dataDetectorTypes = UIDataDetectorTypeLink;
    self.quesDescText.delegate = self;  //实现代理<UITextViewDelegate>    [self.contentView addSubview:self.quesDescText];

其中UITextView的内容需要用NSAttributedString来完成如下所示,这样url点击可以避免直接用NSString两个url相连等异常情况的出现:

NSAttributedString * attrStr = [[NSAttributedString alloc] initWithData:[replyTextString dataUsingEncoding:NSUnicodeStringEncoding] options:@{ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType } documentAttributes:nil error:nil];
self.quesDescText.text = [attrStr string];

(2)使用safari打开url,需实现以下delegate方法

- (BOOL)textView:(UITextView *)textView shouldInteractWithURL:(NSURL *)URL inRange:(NSRange)characterRange NS_AVAILABLE_IOS(7_0) {
    return YES;
}

(3) 在App内打开url

- (BOOL)textView:(UITextView *)textView shouldInteractWithURL:(NSURL *)URL inRange:(NSRange)characterRange NS_AVAILABLE_IOS(7_0) {
    //(省略)用push 或者 present方法,用UIWebViewController打开URL代码
    return NO;
}