美文网首页
UITextView添加超链接及屏蔽选中复制

UITextView添加超链接及屏蔽选中复制

作者: SPKane | 来源:发表于2018-12-07 17:01 被阅读7次

    由于业务需要搞个文字跳转网页,网上的版本很多都很复杂,记录个简单版本的.

    1.首先创建个UITextView的子类.

    如果需要滑动View可以把-(void)addGestureRecognizer:(UIGestureRecognizer *)gestureRecognizer注释取消.

    @implementation UITextLinkView: UITextView
    
    - (BOOL)canBecomeFirstResponder
    {
        return NO;
    }
    
    - (UITextRange *)selectedTextRange{
        return nil;
    }
    
    -(void)addGestureRecognizer:(UIGestureRecognizer *)gestureRecognizer{
       取消所有手势,如果需要其他的可以打开注释.
       //  if ([gestureRecognizer isKindOfClass:[UILongPressGestureRecognizer class]] ) {
         //   gestureRecognizer.enabled = NO;
       //}
       // [super addGestureRecognizer:gestureRecognizer];
    }
    @end
    

    2.创建textView

    _detailTextView = [UITextLinkView new]; 
    _detailTextView.textAlignment = NSTextAlignmentLeft;
    // 修改可点击文字的颜色
        _detailTextView.linkTextAttributes = @{NSForegroundColorAttributeName:[UIColor redColor],NSUnderlineStyleAttributeName:@(1)}; 
        _detailTextView.editable = NO;
        _detailTextView.scrollEnabled = NO;
    //让textVIew文字内容边距为0,便于设置约束.
        _detailTextView.textContainerInset = UIEdgeInsetsMake(0, 0, 0, 0);
    

    3.添加文字

    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
     paragraphStyle.lineSpacing = 2; // 行间距
    NSString * contentStr = @"啦啦啦";
     NSString * jumpStr = @"点我跳转";
    NSString * urlStr = @"http://www.baidu.com";
     contentStr = [ contentStr stringByAppendingString:jumpStr];
    //这步是防止点击链接后如果没有文字,那么点击textVIew后面的空白区域也会跳转
       contentStr = [ contentStr stringByAppendingString:@" "];
     NSDictionary *attributes = @{
     NSForegroundColorAttributeName:[UIColor blackColor],
     NSParagraphStyleAttributeName:paragraphStyle};
     NSMutableAttributedString * attrStr = [[NSMutableAttributedString alloc] initWithString:contentStr attributes:attributes];
    //添加跳转文字及跳转链接
             [attrStr addAttribute:NSLinkAttributeName value:urlStr range:[contentStr rangeOfString:jumpStr]];
     _detailTextView.attributedText = attrStr;
    

    相关文章

      网友评论

          本文标题:UITextView添加超链接及屏蔽选中复制

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