富文本添加可点击事件

一、点击到转到网页类型

如下代码:

    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:@"这是一段可点击的文字,点击百度去浏览网页吧"];
    [attributedString addAttribute:NSLinkAttributeName
                             value:@"https://www.baidu.com"
                             range:[[attributedString string] rangeOfString:@"百度"]];
    [attributedString addAttribute:NSFontAttributeName
                             value:[UIFont systemFontOfSize:20]
                             range:NSMakeRange(0, attributedString.length)];
    self.textview.attributedText = attributedString;
    self.textview.linkTextAttributes = @{NSForegroundColorAttributeName: [UIColor blueColor], NSUnderlineColorAttributeName: [UIColor lightGrayColor],NSUnderlineStyleAttributeName: @(NSUnderlinePatternSolid)};

因为是使用textView来显示的,所以要把textView的editablescrollEnabled设置为NO.效果如下:

AC8AFABA23F47807D1F314EFB0304BB1.png
IMG_1702.PNG
二、执行自定义点击事件类型
    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:@"这是一段可点击的文字,点击百度去浏览网页吧,当然你也可以点击自定义来执行用户事件!"];
    [attributedString addAttribute:NSLinkAttributeName
                             value:@"https://www.baidu.com"
                             range:[[attributedString string] rangeOfString:@"百度"]];
    [attributedString addAttribute:NSLinkAttributeName
                             value:@"CustomTapEvents://"
                             range:[[attributedString string] rangeOfString:@"自定义"]];
    [attributedString addAttribute:NSFontAttributeName
                             value:[UIFont systemFontOfSize:20]
                             range:NSMakeRange(0, attributedString.length)];
    self.textview.attributedText = attributedString;
    self.textview.linkTextAttributes = @{NSForegroundColorAttributeName: [UIColor blueColor],
                                          NSUnderlineColorAttributeName: [UIColor lightGrayColor],
                                          NSUnderlineStyleAttributeName: @(NSUnderlinePatternSolid)};

    self.textview.delegate = self;
    self.textview.editable = NO;
    self.textview.scrollEnabled = NO;

代理方法:

- (BOOL)textView:(UITextView *)textView shouldInteractWithURL:(NSURL *)URL inRange:(NSRange)characterRange {
    if ([[URL scheme] isEqualToString:@"CustomTapEvents"]) {
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:@"用户点击了自定义事件" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:nil];
        [alertController addAction:action];
        [self presentViewController:alertController animated:YES completion:nil];
        return NO;
    }
    return YES;
}

效果图:

IMG_1703.PNG

如有不足之处,还请多多指教。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容