【iOS开发】如何给字符串添加超连接(响应事件)

首先,我们在开发的过程中,会遇到这样的问题。比如:点击某一部分的文字跳转到另一界面。无论是登录协议,保险协议等等吧。

点击用户协议——》跳转协议界面

但是UITextView提供了添加超连接的方法,ios7.0之后使用。或许你可以使用UILabel属性字符串和UIButton来实现,当然是想的方法多种。我就不在介绍了^_^

我来介绍一下UITextView的使用方法:

/**
 *  @author wumeng, 16-06-29 17:06:25
 *
 *  @brief 创建textView
 */
-(void)createTextView
{
    //字符串的处理
    NSString *str  =@"@百度是大坏蛋@www.baidu.com";
    NSString *matchStr = @"百度";
    NSMutableAttributedString *MAttributedString = [[NSMutableAttributedString alloc]initWithString:str];
    
    if ([str rangeOfString:matchStr].location!=NSNotFound) {
        /**
         *  注意这个url必须是*****://***的格式不然url取不到字符串
         */
        [MAttributedString addAttribute:NSLinkAttributeName value:[NSURL URLWithString:@"username://"] range:[[MAttributedString string] rangeOfString:matchStr]];
    }

    //UITextView的创建
    UITextView *TV = [[UITextView alloc]initWithFrame:CGRectMake(0, 60, 300, 200)];
    TV.backgroundColor = [UIColor grayColor];
    //必须设为NO不然不能响应点击事件
    TV.editable = NO;
    //    设置点击时的样式
    NSDictionary *linkAttributes =@{NSForegroundColorAttributeName: [UIColor greenColor],NSUnderlineColorAttributeName: [UIColor lightGrayColor],NSUnderlineStyleAttributeName:@(NSUnderlinePatternSolid)};
    
    //    添加链接文字
    TV.linkTextAttributes = linkAttributes;
    /** 设置自动检测类型为链接网址. */
    TV.dataDetectorTypes = UIDataDetectorTypeLink;
    TV.delegate = self;
    TV.attributedText = MAttributedString;
    
    [self.view addSubview:TV];
    
}
#pragma mark - textViewDelegate
- (BOOL)textView:(UITextView *)textView shouldInteractWithURL:(NSURL *)URL inRange:(NSRange)characterRange
{
    NSLog(@"%@",[URL scheme]);
    if ([[URL scheme] containsString:@"username"]) {
        NSLog(@"点中了。。。。。。。。");
    }
    return YES;//跳转到浏览器
}
不过你们可以把它封装成一个类来使用,不过也有几个需要注意的点

添加属性链接的URL需要注意的地方,必须使用xxxx://xxxx的格式。

/**
         *  注意这个url必须是<span style="background-color: rgb(255, 102, 102);">*****://***</span>的格式不然url取不到字符串
         */
        [MAttributedString addAttribute:NSLinkAttributeName value:[NSURL URLWithString:@"username://"] range:[[MAttributedString string] rangeOfString:matchStr]];

在代理方法回调的时候,如果没有“ ://”的话,在[URL scheme]方法里取不到特定的值,一句话 ://前面的才是最重要的标识符


  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

WMSmile

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值