首先你需要第三方RegexKitLite以及YYKit
1. 我們先來說說RegexKitLite的導(dǎo)入
你可以在github上下載并導(dǎo)入你的項(xiàng)目,也可以用cocopods導(dǎo)入娃肿。
-
使用cocopods
這樣相對來說比較簡單胁赢,不用管其他配置了 - 從github下載 RegexKitLite導(dǎo)入你的項(xiàng)目中痕支,然后你需要配置以下:
Build Phases需要配置
2. 至于YYKit啃勉,同樣你可以選擇手動導(dǎo)入或者cocopods第三方管理工具
- 使用cocopods
- 在podfile中添加 pod ‘YYKit’
- 執(zhí)行pod install
- 手動安裝
- 下載YYKit并將YYKit中源文件拖放如你的工程
- 為 NSObject+YYAddForARC.m 和 NSThread+YYAdd.m 添加編譯參數(shù) -fno-objc-arc
- 鏈接以下 frameworks:
- UIKit
- CoreFoundation
- CoreText
- CoreGraphics
- CoreImage
- QuartzCore
- ImageIO
- AssetsLibrary
- Accelerate
- MobileCoreServices
- SystemConfiguration
- sqlite3
- libz
接下來就是我們需要做的就是代碼搞起來
1. 導(dǎo)入頭文件
#import "RegexKitLite.h"
#import "YYKit.h"
2. 主要代碼
NSString *regex_http = @"<a href=(?:.*?)>(.*?)<\\/a>";
NSString *labelText = @"<a href=\"http://www.baidu.com\" target=\"_blank\">快件查詢頁面</a>";
NSArray *array_http = [labelText arrayOfCaptureComponentsMatchedByRegex:regex_http];
// 高亮狀態(tài)的背景
YYTextBorder *highlightBorder = [YYTextBorder new];
highlightBorder.insets = UIEdgeInsetsMake(-2, 0, -2, 0);
highlightBorder.cornerRadius = 3;
highlightBorder.fillColor = [UIColor lightGrayColor];
if ([array_http count]) {
// 先把html a標(biāo)簽都給去掉
labelText = [labelText stringByReplacingOccurrencesOfString:@"<a href=(.*?)>" withString:@"" options:NSRegularExpressionSearch range:NSMakeRange (0, labelText.length)];
labelText = [labelText stringByReplacingOccurrencesOfString:@"<\\/a>" withString:@"" options:NSRegularExpressionSearch range:NSMakeRange (0, labelText.length)];
NSLog(@"labelText === %@", labelText);
NSMutableAttributedString *aStr = [[NSMutableAttributedString alloc] initWithString:labelText];
aStr.font = [UIFont systemFontOfSize:14];
aStr.color = [UIColor blackColor];
for (NSArray *array in array_http) {
// 獲得鏈接顯示文字的range埠巨,用來設(shè)置下劃線
NSRange range = [labelText rangeOfString:array[1]];
[aStr setColor:[UIColor blueColor] range:range];
// 高亮狀態(tài)
YYTextHighlight *highlight = [YYTextHighlight new];
[highlight setBackgroundBorder:highlightBorder];
// 數(shù)據(jù)信息义辕,用于稍后用戶點(diǎn)擊
NSString *linkStr = [array.firstObject componentsSeparatedByString:@"\""][1];
highlight.userInfo = @{@"linkUrl": linkStr};
[aStr setTextHighlight:highlight range:range];
}
_herfLabel.attributedText = aStr;
}
_herfLabel.highlightTapAction = ^(UIView * _Nonnull containerView, NSAttributedString * _Nonnull text, NSRange range, CGRect rect){
text = [text attributedSubstringFromRange:range];
NSDictionary *dic = text.attributes;
YYTextHighlight *user = [dic valueForKey:@"YYTextHighlight"];
NSString *linkText = [user.userInfo valueForKey:@"linkUrl"];
NSLog(@"獲取的linkText:%@ 在這里可以跳轉(zhuǎn)界面", linkText);
};
提示:_herfLabel是YYLabel套像,不是普通的UILabel
最后,下次有時(shí)間會附上demo终息。