• 将UILabel或UITextView中的文字设置为超链接


    将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];
    }
    }
  • 相关阅读:
    oc-25-id类型,
    oc-25-id类型
    [转贴]systemd 编写服务管理脚本
    [转贴]infoQ VSTS被拆成5个部分,以Azure DevOps服务形式推出
    Oracle 数据库备份启用压缩以及remap
    Support for SSL/TLS protocols on Windows
    微软自己的官网介绍 SSL 参数相关
    .NET4.0 加密通讯协议下TLS 的兼容支持问题.
    使用Word 进行UTF8 以及字符串编码的转换操作
    计算机管理以及设备管理的快捷打开方式
  • 原文地址:https://www.cnblogs.com/sunyanyan/p/5284396.html
Copyright © 2020-2023  润新知