代码片段iOS开发

富文本添加可点击事件

2017-05-17  本文已影响56人  ZYiDa
一、点击到转到网页类型

如下代码:

    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

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

上一篇下一篇

猜你喜欢

热点阅读