最近做UIlabel的超链接显示,用到了MZSelectableLabel,下面给大家介绍一下使用方法。
首先从网上下载MZSelectableLabel导入项目,就是下图的四个文件
下面给大家看一下使用方法,这里介绍的时通过正则表达式识别超链接,当然你也可以自己建立超链接,并进行跳转;
首先初始化
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];
};
}
}
效果如下图:
";