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

IOS 中给富文本添加点击事件

作者: lenka01 | 来源:发表于2019-03-19 19:08 被阅读0次

利用textView的可编辑模式从而可以达到此效果。

    self.textView = [[UITextView alloc] init];
    self.textView.layer.borderColor = [UIColor blackColor].CGColor;
    self.textView.layer.borderWidth = 1.0;
    self.textView.frame = CGRectMake(30, 100, CGRectGetWidth(self.view.bounds)-60, 500);
    self.textView.editable = false;
    self.textView.scrollEnabled = false;
    self.textView.delegate = self;
    [self.view addSubview:self.textView];
    //设置段落样式
    NSMutableParagraphStyle *paragraphStyle = [NSMutableParagraphStyle new];
    paragraphStyle.lineBreakMode = NSLineBreakByCharWrapping;
    paragraphStyle.lineSpacing = 4.0;//段内行间距
    paragraphStyle.paragraphSpacing = 8.0;//段落间距
    paragraphStyle.firstLineHeadIndent = 20.0;//段首行缩进
    NSMutableAttributedString *mutAttString = [[NSMutableAttributedString alloc] initWithString:text];
    [mutAttString addAttributes:@{
                                  NSParagraphStyleAttributeName:paragraphStyle,
                                  NSFontAttributeName:[UIFont systemFontOfSize:18]
                                  } range:NSMakeRange(0, mutAttString.length)];
    [mutAttString addAttributes:@{
                                  NSForegroundColorAttributeName:[UIColor blueColor],
                                  NSLinkAttributeName:@"abcd://",
                                  NSUnderlineStyleAttributeName:@(NSUnderlineStyleSingle),
                                  NSUnderlineColorAttributeName:[UIColor blueColor],
                                  } range:NSMakeRange(text.length-22, 12)];
    self.textView.attributedText = mutAttString;

实现代理方法,很关键

#pragma mark - UITextViewDelegate
- (BOOL)textView:(UITextView *)textView shouldInteractWithURL:(NSURL *)URL inRange:(NSRange)characterRange interaction:(UITextItemInteraction)interaction
{
    NSLog(@"shouldInteractWithURL");
    return NO;//这里返回NO可以避免长按连接弹出actionSheet框
}
image.png

相关文章

网友评论

    本文标题:IOS 中给富文本添加点击事件

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