UITextView中部分字段加点击事件

在日常开发中,我们会遇到这样的需求,就是一段文字说明中的某一段字是要有点击事件的,并且颜色也要跟整段文字区分开来,这时候用textView就比较方便了,效果如下:
效果图.png

首先给一个textView的内容:

static NSString *content = @"•  原手机号码无法收到验证码?  点击 其他方式修改\n•  如需帮助,请联系客服 010-123456 查询。";

然后设置下textView的属性

// 设置属性
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    // 设置行间距
    paragraphStyle.paragraphSpacing = 2; // 段落间距
    paragraphStyle.lineSpacing = 1;      // 行间距
    NSDictionary *attributes = @{
                                 NSForegroundColorAttributeName:[UIColor blackColor],
                                 NSParagraphStyleAttributeName:paragraphStyle
                                 };
    NSMutableAttributedString * attrStr = [[NSMutableAttributedString alloc] initWithString:message attributes:attributes];
    [attrStr addAttributes:@{
                             NSLinkAttributeName:@"其他方式修改"
                             }
                     range:[message rangeOfString:@"其他方式修改"]];
    [attrStr addAttributes:@{
                             NSLinkAttributeName:@"telprompt://010-123456"
                             }
                     range:[message rangeOfString:@"010-123456"]];
    _textView.linkTextAttributes = @{NSForegroundColorAttributeName:[UIColor blueColor]}; // 修改可点击文字的颜色
    _textView.attributedText = attrStr;
    _textView.editable = NO;
    _textView.scrollEnabled = NO;
    _textView.delegate = self;

电话是可以直接拨打的,但是如果是一段文字,我们就需要去代理方法里实现我们要做的事:

// 其他方式修改
-(BOOL)textView:(UITextView *)textView shouldInteractWithURL:(NSURL *)URL inRange:(NSRange)characterRange {
    NSRange range = [content rangeOfString:@"其他方式修改"];
    if (characterRange.location == range.location) {
        // 做你想做的事
    }
    return YES;
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

友情链接更多精彩内容