iOS开发UITextView添加超链接,屏蔽选中复制

释放双眼,带上耳机,听听看~!

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

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;

 

人已赞赏
iOS文章

iOS开发自定义推送提示音

2021-2-4 5:07:25

iOS文章

iOS中图片的渲染过程(从解压到渲染)

2021-2-4 6:22:38

0 条回复 A文章作者 M管理员
    暂无讨论,说说你的看法吧
个人中心
购物车
优惠劵
今日签到
有新私信 私信列表
搜索