美文网首页iOS新手学习
iOS富文本添加点击事件

iOS富文本添加点击事件

作者: 十三楼的大笨象 | 来源:发表于2019-07-09 11:31 被阅读0次

公司项目中需要在登录界面加一个隐私政策的入口,类似于“阅读并同意\color{red}{《XXX隐私政策》}”,最开始的做法比较简单粗暴直接用按钮设置富文本显示,但是有一个不好的体验就是点击前面的“阅读并同意”也会跳进隐私政策页面。最近有时间对这个做了下优化,才有了UITextView显示并添加富文本链接的做法,代码如下:

    UITextView *protocolTV = [[UITextView alloc] init];
    protocolTV.frame = CGRectMake(15, 15, SCREENWIDTH-30, 40);
    protocolTV.editable = NO;
    protocolTV.delegate = self;
//去除左右边距
    protocolTV.textContainer.lineFragmentPadding = 0.0;
//设置垂直居中
    protocolTV.textContainerInset = UIEdgeInsetsMake(15, 0, 0, 0);
//设置添加链接部分文字的颜色,即“《XXX隐私政策》”
    protocolTV.linkTextAttributes = @{NSForegroundColorAttributeName:[ColorExt appStyleColor]};
    [self.view addSubview:protocolTV];
    
    NSString *appName = [NSBundle mainBundle].infoDictionary[@"CFBundleDisplayName"];
    NSString *rangeStr = [NSString stringWithFormat:@"《%@隐私政策》",appName];
    NSString *protocolStr = [NSString stringWithFormat:@"阅读并同意%@",rangeStr];
    NSRange privacyRange = [protocolStr rangeOfString:rangeStr];
    NSMutableAttributedString *privacyMutableAttrStr = [[NSMutableAttributedString alloc] initWithString:protocolStr attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:11.0],NSForegroundColorAttributeName:rgba(102, 102, 102, 1)}];
    
  //给需要 点击事件的部分添加链接
    [privacyMutableAttrStr addAttribute:NSLinkAttributeName value:@"privacy://" range:privacyRange];
    protocolTV.attributedText = privacyMutableAttrStr;

通过代理方法来响应具体的点击事件

#pragma mark - UITextViewDelegate
-(BOOL)textView:(UITextView *)textView shouldInteractWithURL:(NSURL *)URL inRange:(NSRange)characterRange{
    if ([URL.scheme isEqualToString:@"privacy"]) {
//这里调用方法跳到隐私政策页面
        [self protocolBtnClick];
        return NO;
    }
    
    return YES;
}

这就是我实现该功能的做法,中间也遇到了一些问题,如下:
1.默认给文字添加链接之后文字显示是蓝色的,直接用属性字符串的NSForegroundColorAttributeName修改颜色没有效果,必须使用UITextView的linkTextAttributes属性在这里面设置链接文字的颜色和字体等。

2.左边不对齐,因为UITextView默认左右会有内边距,为了左边对齐,你必须设置 protocolTV.textContainer.lineFragmentPadding = 0.0。

3.不垂直居中,UITextView默认不会垂直居中,要想达到垂直居中的效果需要设置 protocolTV.textContainerInset = UIEdgeInsetsMake(15, 0, 0, 0);调整上边的内边距的值来达到垂直居中的效果。

相关文章

网友评论

    本文标题:iOS富文本添加点击事件

    本文链接:https://www.haomeiwen.com/subject/uvntkctx.html