开发者社区> 问答> 正文

iOS lable如何实现复制粘贴选择全选

开发中遇到 要求lable 要求可以选择全选 也就是select方法的实现

展开
收起
爵霸 2016-03-11 14:38:33 3092 0
2 条回答
写回答
取消 提交回答
  • 看下这个 https://github.com/solehe/XXAttributedLabel

    2020-03-12 16:50:01
    赞同 展开评论 打赏
  • 代码直接发你,将就着看下 ,自定义一个 uilabel就行

     //
     // Cuslabel.m
     // test
     //
     // Created by mac on 15-3-21.
     // Copyright (c) 2015年 mac. All rights reserved.
     //
    
    #import "Cuslabel.h"
    
    @implementation Cuslabel
    (id)initWithFrame:(CGRect)frame { self = [super initWithFrame:frame]; if (self) { [self attachTapHandler]; } return self; }
    
    /*
     // Only override drawRect: if you perform custom drawing.
     // An empty implementation adversely affects performance during animation.
    (void)drawRect:(CGRect)rect { // Drawing code } */
    
    //为了能接收到事件(能成为第一响应者),我们需要覆盖一个方法:
    
    -(BOOL)canBecomeFirstResponder
     {
     return YES;
     }
    
    //还需要针对复制的操作覆盖两个方法:
    
    // 可以响应的方法
     -(BOOL)canPerformAction:(SEL)action withSender:(id)sender
     {
     return (action == @selector(copy:));
    
    }
    
    //针对于响应方法的实现
     -(void)copy:(id)sender
     {
     UIPasteboard *pboard = [UIPasteboard generalPasteboard];
     pboard.string = self.text;
     }
    
    //有了以上三个方法,我们就能处理copy了,当然,在能接收到事件的情况下:
    
    //UILabel默认是不接收事件的,我们需要自己添加touch事件
     -(void)attachTapHandler
     {
     self.userInteractionEnabled = YES; //用户交互的总开关
     // UITapGestureRecognizer *touch = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTap:)];
     // touch.numberOfTapsRequired = 2;
    UILongPressGestureRecognizer  *jk=[[UILongPressGestureRecognizer alloc]initWithTarget:self action:@selector(handleTap:)];
    [self addGestureRecognizer:jk];
    
    
    // [UIResponder ]
    
    }
     //绑定事件
     -(void)handleTap:(UIGestureRecognizer*) recognizer
     {
     [self becomeFirstResponder];
     // UIMenuItem *copyLink = [[UIMenuItem alloc] initWithTitle:@"复制"
     // action:@selector(copy:)];
     // [[UIMenuController sharedMenuController] setMenuItems:[NSArray arrayWithObjects:copyLink, nil]];
     [[UIMenuController sharedMenuController ] setTargetRect:self.frame inView:self.superview];
     [[UIMenuController sharedMenuController] setMenuVisible:YES animated: YES];
     }
     //同上
     -(void)awakeFromNib
     {
     [super awakeFromNib];
     [self attachTapHandler];
     }
    
    @end
    2019-07-17 18:59:17
    赞同 展开评论 打赏
问答分类:
问答标签:
问答地址:
相关产品:
问答排行榜
最热
最新

相关电子书

更多
手淘iOS性能优化探索 立即下载
From Java/Android to Swift iOS 立即下载
深入剖析iOS性能优化 立即下载