将UILabel或UITextView中的文字设置为超链接
判断是否符合超链接格式
-(BOOL)isUrlValid:(NSString*)urlStr{
NSLog(@" 判断url是否合法 ");
NSError *error;
NSString *regulaStr = @"((http{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* matchedArr = [regex matchesInString:urlStr options:NSMatchingReportProgress range:NSMakeRange(0, urlStr.length)];
if ([matchedArr count] != 0) {
NSLog(@" 符合超链接模式 ");
return true;
}
else{
NSLog(@" 不符合超链接模式 ");
}
return false;
}
使用 Reachability判断url是否可以访问(排除符合超链接格式,但是并不存在的网址)
+(BOOL)isUrlReachable:(NSString*)url{
NSLog(@" 判断url是否可以被访问 ");
NSArray* arr = [url componentsSeparatedByString:@"://"];
if ([arr count] <= 1) return false;
NSString* urlSepStr = [arr objectAtIndex:1];
if(!urlSepStr) return false;
NSLog(@" urlSepStr is %@ ",urlSepStr);
NSArray* arr2 = [urlSepStr componentsSeparatedByString:@"/"];
NSString* urlSepStr2 = [arr2 objectAtIndex:0];
if (!urlSepStr2) return false;
Reachability* reach = [Reachability reachabilityWithHostName:urlSepStr2];
NSInteger status = [ reach currentReachabilityStatus];
NSLog(@" status is %ld ",(long)status);
if (status == NotReachable) return false;
return true;
}
判断是否为超链接并且可以访问
-(BOOL)isUrl:(NSString*)urlStr{
if (![ self isUrlValid:urlStr]) return false;
return [self isUrlReachable:urlStr];
}
将UILabel设置下划线 设置点击事件 = 设置为超链接
-(void)setTitleLabel:(NSString*)urlStr{
if ([self isUrl:urlStr]) {
//变蓝 显示下划线
self.label.textColor = [UIColor blueColor];
NSMutableAttributedString *content = [[NSMutableAttributedString alloc] initWithString:self.label.text];
NSRange contentRange = {0, [content length]};
[content addAttribute:NSUnderlineStyleAttributeName value:[NSNumber numberWithInteger:NSUnderlineStyleSingle] range:contentRange];
self.label.attributedText = content;
//添加点击事件
self.label.userInteractionEnabled = true;
UITapGestureRecognizer* tapGes = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(showWebView:)];
[self.label addGestureRecognizer:tapGes];
}
}