基本实现思路就是利用正则识别链接加YYLabel设置链接点击事件,下面说下这过程中遇到的问题
1、自动布局YYLabel后发现设置label.numberOfLines = 0后不换行,YYLabel还得设置一个preferredMaxLayoutWidth属性,这个属性是设置最大宽度,设置完才能有换行功能
2、添加YYLabel的分类并且利用正则识别链接
- (void)setTextWithLinkAttribute:(NSString *)text {
self.userInteractionEnabled = YES;
self.attributedText = [self subStr:text];
}
-(NSMutableAttributedString*)subStr:(NSString *)string {
NSError *error;
//可以识别url的正则表达式
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\\.\\-~!@#$%^&*+?:_/=<>]*)?)";
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:regulaStr
options:NSRegularExpressionCaseInsensitive
error:&error];
NSArray *arrayOfAllMatches = [regex matchesInString:string options:0 range:NSMakeRange(0, [string length])];
NSMutableArray *arr=[[NSMutableArray alloc]init];
NSMutableArray *rangeArr=[[NSMutableArray alloc]init];
for (NSTextCheckingResult *match in arrayOfAllMatches) {
NSString* substringForMatch;
substringForMatch = [string substringWithRange:match.range];
[arr addObject:substringForMatch];
}
NSString *subStr = string;
for (NSString *str in arr) {
[rangeArr addObject:[self rangesOfString:str inString:subStr]];
}
UIFont *font = [UIFont systemFontOfSize:14];
NSMutableAttributedString *attributedText;
attributedText = [[NSMutableAttributedString alloc]initWithString:subStr attributes:@{NSFontAttributeName :font}];
for(NSValue *value in rangeArr) {
NSInteger index=[rangeArr indexOfObject:value];
NSRange range=[value rangeValue];
// [attributedText addAttribute:NSLinkAttributeName value:[NSURL URLWithString:[arr objectAtIndex:index]] range:range];
// [attributedText addAttribute:NSForegroundColorAttributeName value:[UIColor blueColor] range:range];
[attributedText setTextHighlightRange:range
color:[UIColor blueColor]
backgroundColor:[UIColor clearColor]
tapAction:^(UIView * _Nonnull containerView, NSAttributedString * _Nonnull text, NSRange range, CGRect rect) {
NSString *str = text.string;
NSString *urlStr = [str substringWithRange:range];
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:urlStr] options:@{} completionHandler:^(BOOL success) {
}];
}];
}
return attributedText;
}
//获取查找字符串在母串中的NSRange
- (NSValue *)rangesOfString:(NSString *)searchString inString:(NSString *)str {
NSRange searchRange = NSMakeRange(0, [str length]);
NSRange range;
if ((range = [str rangeOfString:searchString options:0 range:searchRange]).location != NSNotFound) {
searchRange = NSMakeRange(NSMaxRange(range), [str length] - NSMaxRange(range));
}
return [NSValue valueWithRange:range];
}
3、通过给NSAttributedString设置高亮并且添加点击事件
[attributedText setTextHighlightRange:range
color:[UIColor blueColor]
backgroundColor:[UIColor clearColor]
tapAction:^(UIView * _Nonnull containerView, NSAttributedString * _Nonnull text, NSRange range, CGRect rect) {
NSString *str = text.string;
NSString *urlStr = [str substringWithRange:range];
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:urlStr] options:@{} completionHandler:^(BOOL success) {
}];
}];
4、添加完点击事件后点击发现并没有响应,是因为label的父类试图添加了点击手势导致的手势冲突解决办法是给父试图的手势添加代理并且实现代理方法
func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool {
var isCanRecognize = true //是否能被识别
if ((touch.view as? YYLabel) != nil) {
let label = touch.view as! YYLabel
let attributedString = label.textLayout?.text
let index : NSInteger? = label.textLayout?.textRange(at: touch.location(in: label))?.start.offset
if index != nil, index! > 0 {
let highlight = attributedString?.attribute(YYTextHighlightAttributeName, at: UInt(index!))
isCanRecognize = highlight != nil ? false : true
}
}
return isCanRecognize
}