最近做UIlabel的超鏈接顯示,用到了MZSelectableLabel,下面給大家介紹一下使用方法。
首先從網上下載MZSelectableLabel導入項目,就是下圖的四個文件
文件截圖.png
下面給大家看一下使用方法,這里介紹的時通過正則表達式識別超鏈接,當然你也可以自己建立超鏈接,并進行跳轉;
首先初始化
MZSelectableLabel *_itemDetailLabel =[ [MZSelectableLabel alloc] init];
_itemDetailLabel.text = @"nihaomahttp://www.baidu.com你好";
[self.view addSubview:_itemDetailLabel];
[self urlValidation:_itemDetailLabel.text];
實現urlValidation方法如下:
- (void)urlValidation:(NSString *)string {
string = [string stringByReplacingOccurrencesOfString:@" " withString:@""];
NSError *error;
//識別鏈接的正則表達式
NSString *regulaStr = @"((http[s]{0,1}|ftp)://[a-zA-Z0-9\\.\\-]+\\.([a-zA-Z]{2,4})(:\\d+)?(/[a-zA-Z0-9\\.\\-~!@#$%^&*+?:_/=<>]*)?)|(www.[a-zA-Z0-9\\.\\-]+\\.([a-zA-Z]{2,4})(:\\d+)?(/[a-zA-Z0-9\\.\\-~!@#$%^&*+?:_/=<>]*)?)";
//與string做對比并獲得超鏈接在string中的位置
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:regulaStr options:NSRegularExpressionCaseInsensitive error:&error];
NSArray *arrayOfAllMatches = [regex matchesInString:string options:0 range:NSMakeRange(0, [string length])];
NSMutableArray *urlStrs = [NSMutableArray array];
NSMutableArray *urlRanges = [NSMutableArray array];
// 行間距
NSMutableParagraphStyle * paragraphStyle = [[NSMutableParagraphStyle alloc] init];
[paragraphStyle setLineSpacing:8];
NSDictionary *allPerferDic = @{
NSForegroundColorAttributeName : [UIColor colorWithHexString:@"#646464"],
NSFontAttributeName : [UIFont systemFontOfSize:14.0f],
NSParagraphStyleAttributeName : paragraphStyle
};
NSMutableAttributedString *mas = [[NSMutableAttributedString alloc] initWithString:string];
[mas setAttributes:allPerferDic range:NSMakeRange(0, string.length)];
for (NSTextCheckingResult *match in arrayOfAllMatches){
NSString* substringForMatch = [string substringWithRange:match.range];
NSURL *url = [NSURL URLWithString:substringForMatch];
if (!url) {continue;}
[urlStrs addObject:[NSURL URLWithString:substringForMatch]];
[urlRanges addObject:[NSValue valueWithRange:match.range]];
}
[urlRanges enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop){
[mas addAttributes:@
{
NSForegroundColorAttributeName : [UIColor colorWithHexString:@"#15B1FF"],
NSFontAttributeName : [UIFont systemFontOfSize:14.0]
} range:[obj rangeValue]];
}];
_itemDetailLabel.attributedText = mas;
_itemDetailLabel.userInteractionEnabled = YES;
if (!urlStrs.count) { return;}
for (int i = 0; i<urlStrs.count; i++) {
NSRange range = [urlRanges[i] rangeValue];
//設置超鏈接選中后的背景色
[_itemDetailLabel setSelectableRange:range hightlightedBackgroundColor:[UIColor lightGrayColor]];
//實現超鏈接將要實現的方法,這里我寫了一個通知來跳轉界面,也可以寫其他跳轉方法
_itemDetailLabel.selectionHandler = ^(NSRange range, NSString *string){
NSLog(@"%@",string);
[[NSNotificationCenter defaultCenter] postNotificationName:@"LinkAccess" object:string];
};
}
}
效果如下圖:
Snip20161125_1.png
";