iOS Label 長按拷貝、粘貼、剪切的實現(xiàn)

代碼如下(這里是延展的 .m 文件中實現(xiàn)部分):

@implementation CustomEditLabel

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

- (void)awakeFromNib{
    [super awakeFromNib];
    
    [self addLongPressEvent];
}
- (instancetype)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self) {

        [self addLongPressEvent];
    }
    return self;
}

- (void)addLongPressEvent{
    
    self.userInteractionEnabled = YES;
    UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(actionS:)];
    [self addGestureRecognizer:longPress];
    
}


- (void)actionS:(UILongPressGestureRecognizer *)gesture{
    
    if (gesture.state == UIGestureRecognizerStateBegan) {
    
    [self becomeFirstResponder];
    UIMenuItem *menuItem1 = [[UIMenuItem alloc] initWithTitle:@"拷貝哦" action:@selector(copyS:)];
    UIMenuItem *menuItem2 = [[UIMenuItem alloc] initWithTitle:@"粘貼哦" action:@selector(pasteS:)];
    UIMenuItem *menuItem3 = [[UIMenuItem alloc] initWithTitle:@"剪切哦" action:@selector(cutS:)];
    UIMenuController *menuC = [UIMenuController sharedMenuController];

    menuC.menuItems = @[menuItem1, menuItem2, menuItem3];
    menuC.arrowDirection = UIMenuControllerArrowUp;
    
    if (menuC.menuVisible) {
//        NSLog(@"menuC.menuVisible    判斷 --  %d", menuC.menuVisible);
        return ;
    }
    
    [menuC setTargetRect:self.frame inView:self.superview];
    [menuC setMenuVisible:YES animated:YES];
        
   }
}

- (BOOL)canBecomeFirstResponder{
    return YES;
    
}

- (BOOL)canPerformAction:(SEL)action withSender:(id)sender{
    
    if ( action == @selector(copyS:)  || (action == @selector(pasteS:) && [UIPasteboard generalPasteboard].string) || action == @selector(cutS:) ) {
//        NSLog(@"粘貼板   --  %@", [UIPasteboard generalPasteboard].string);
        return YES;
    }else{
        return NO;
    }
}
//剪切事件(暫時不用)
- (void)cutS:(id)sender{
    
    UIPasteboard *pboard = [UIPasteboard generalPasteboard];
    pboard.string = self.text;
    //剪切 功能
    self.text = nil;
}

//拷貝
- (void)copyS:(id)sender{
    
    UIPasteboard *pboard = [UIPasteboard generalPasteboard];
    pboard.string = self.text;
    
}
//粘貼
- (void)pasteS:(id)sender{
    
    UIPasteboard *pboard = [UIPasteboard generalPasteboard];
    self.text = pboard.string;
}


@end

有不完整的地方請多多指教 。。。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容