/**
* 功能:从父串中搜索指定的所有子串,并返回子串所处的位置和长度->NSRange对象
*
* 思路:从父串中搜索给定的子串,调用rangeOfString Option Range方法,返回本次搜索结果,
* 如果结果的location不为NSNotFound,就表示本次搜索是成功获取到子串的,那么继续缩小
* 搜索范围,从本次搜索结果的location开始,搜索长度为父串长度减去子串的长度,每次搜索完
* 毕后,都对搜索范围重新设置(PS:设置搜索范围时,每次加1个单位长度和每次加一个子串的长度的区别
* 在于:前者是遍历父串中包含的子串个数,包括重叠的子串,如"ababa"包含两个"aba"子串,这种情况
* 比较适合考试,实际应用中很少有这种需求. 而后者只遍历不重叠的子串,父串"ababa"只包含一个"aba",
* 子串,这种情况在实际应用比较常见,例如,我们在百度搜索中搜索"OC"关键字,一篇文章中的"OC"两个字母都
* 会显示为红色)
* 应用:话不多说,实际操作一把
*
*/
NSString *fatherString = @"abababadef";
NSRange searchRange = NSMakeRange(0, fatherString.length);
while (searchRange.location != NSNotFound) {
searchRange = [fatherString rangeOfString:@"aba" options:0 range:searchRange];
NSLog(@"%@",NSStringFromRange(searchRange));
if(searchRange.location != NSNotFound){
searchRange = NSMakeRange(searchRange.location+1, fatherString.length-searchRange.location-1);
}
}
/**
* 实际应用:阅读文章时,有时候某个关键字是一个链接,点击可以实现跳转URL事件(PS:当然,我们可以拦截代理点击事件,增加额外的操作)
*/
NSString *fatherString = @"例如,我们在百度搜索中搜索\"OC\"关键字,一篇文章中的\"OC\"两个字母都会显示为红色";
NSMutableAttributedString *attriFatherStr = [[NSMutableAttributedString alloc]initWithString:fatherString];
NSDictionary *attriDic = @{
NSForegroundColorAttributeName:kRedColor,
NSFontAttributeName:[UIFont systemFontOfSize:20],
NSLinkAttributeName:@"http://www.jianshu.com/p/9ffcdc0003e0"
};
NSRange searchRange = NSMakeRange(0, fatherString.length);
while (searchRange.location != NSNotFound) {
searchRange = [fatherString rangeOfString:@"\"OC\"" options:0 range:searchRange];
[attriFatherStr setAttributes:attriDic range:searchRange];
if(searchRange.location != NSNotFound){
searchRange = NSMakeRange(searchRange.location+2, fatherString.length-searchRange.location-2);
}
}
UITextView *textView = [[UITextView alloc]init];
[self addSubview:textView];
textView.frame= CGRectMake(100, 100, 200, 100);
textView.backgroundColor = [UIColor clearColor];
textView.editable = NO;
textView.delegate = self;
textView.dataDetectorTypes = UIDataDetectorTypeLink;
textView.attributedText =attriFatherStr;
#pragma mark - Delegate
/**
* 代理方法,可拦截点击url的事件,
*/
-(BOOL)textView:(UITextView *)textView shouldInteractWithURL:(NSURL *)URL inRange:(NSRange)characterRange{
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:NSStringFromRange(characterRange) delegate:self cancelButtonTitle:@"确定" otherButtonTitles: nil];
[alert show];
return NO;
}