在项目中经常有识别文本中url并可以点击进行网页链接的需求。我们需要适当的处理带url的字符串
代码如下:
-(void)createUI
{
textView=[[UITextView alloc]initWithFrame:CGRectMake(18, 100, self.view.bounds.size.width-36, 100)];
[textView setEditable:NO];
[self.view addSubview:textView];
[self subStr:@"我是一段中文https://github.com/TinyQ我还是一段中文阿里科技屌丝拉法基是拉萨江东父老阿斯蒂芬阿斯蒂芬四缸发动机https://www.baidu.com发送"];
}
-(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])];
//NSString *subStr;
NSMutableArray *arr=[[NSMutableArray alloc]init];
NSArray *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)
{
subStr=[subStr stringByReplacingOccurrencesOfString:str withString:@"网页链接"];
}
rangeArr=[self rangesOfString:@"网页链接" inString:subStr];
// //计算大小
UIFont *font = [UIFont systemFontOfSize:15];
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:[NSString stringWithFormat:@"%@",[arr objectAtIndex:index]]] range:range];
}
return attributedText;
}
//获取查找字符串在母串中的NSRange
- (NSArray *)rangesOfString:(NSString *)searchString inString:(NSString *)str {
NSMutableArray *results = [NSMutableArray array];
NSRange searchRange = NSMakeRange(0, [str length]);
NSRange range;
while ((range = [str rangeOfString:searchString options:0 range:searchRange]).location != NSNotFound) {
[results addObject:[NSValue valueWithRange:range]];
searchRange = NSMakeRange(NSMaxRange(range), [str length] - NSMaxRange(range));
}
return result