要找到一段字符串中的網址位置,可以用正則表達式,正則表達式比較麻煩,蘋果有自帶的API:NSDataDetector用方法+ (nullable NSDataDetector *)dataDetectorWithTypes:(NSTextCheckingTypes)checkingTypes error:(NSError **)error;可以看到在類NSTextCheckingTypes中的NSTextCheckingTypeLink既是檢測URL的,當然裏面還有很多類型
NSTextCheckingTypeOrthography // language identification
NSTextCheckingTypeSpelling // spell checking
NSTextCheckingTypeGrammar // grammar checking
NSTextCheckingTypeDate // date/time detection
NSTextCheckingTypeAddress // address detection
NSTextCheckingTypeLink // link detection
NSTextCheckingTypeQuote // smart quotes
NSTextCheckingTypeDash // smart dashes
NSTextCheckingTypeReplacement // fixed replacements, such as copyright symbol for (c)
NSTextCheckingTypeCorrection // autocorrection
NSTextCheckingTypeRegularExpression // regular expression matches
NSTextCheckingTypePhoneNumber // phone number detection
NSTextCheckingTypeTransitInformation // transit (e.g. flight) info detection
我只介紹URL的識別,其他的原理都一樣的,隨便找一個字符串
NSString *webString = @"這不是網址\"http://www.baidu.com\"這是我大百度帝國"; [self needHightText:webString];
- (void)needHightText:(NSString *)wholeText {
// 點擊事件用的YYLabel框架,
YYLabel *mainLabel = [[YYLabel alloc]initWithFrame:CGRectMake(0, 100, 400, 100)];
[self.view addSubview:mainLabel];
mainLabel.numberOfLines = 0;
mainLabel.textColor = [UIColor purpleColor];
NSMutableAttributedString *text = [[NSMutableAttributedString alloc]initWithString:wholeText];
text.yy_font = [UIFont systemFontOfSize:17];
NSError *error;
NSDataDetector *dataDetector=[NSDataDetector dataDetectorWithTypes:NSTextCheckingTypeLink error:&error];
NSArray *arrayOfAllMatches=[dataDetector matchesInString:wholeText options:NSMatchingReportProgress range:NSMakeRange(0, wholeText.length)];
//NSMatchingOptions匹配方式也有好多種,我選擇NSMatchingReportProgress,一直匹配
//我們得到一個數組,這個數組中NSTextCheckingResult元素中包含我們要找的URL的range,當然可能找到多個URL,找到相應的URL的位置,用YYlabel的高亮點擊事件處理跳轉網頁
for (NSTextCheckingResult *match in arrayOfAllMatches)
{
// NSLog(@"%@",NSStringFromRange(match.range));
[text yy_setTextHighlightRange:match.range//設置點擊的位置
color:[UIColor orangeColor]
backgroundColor:[UIColor whiteColor]
tapAction:^(UIView *containerView, NSAttributedString *text, NSRange range, CGRect rect){
NSLog(@"這裏是點擊事件");
//跳轉用的WKWebView
WKWebView *webView = [[WKWebView alloc] initWithFrame:self.view.bounds];
[self.view addSubview:webView];
[webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:[wholeText substringWithRange:match.range]]]];
}];
}
mainLabel.attributedText = text;
}
過程解釋看代碼中的註釋,此方法用到了YYText框架,記得導入,還有系統自帶的WebKit也需要導入