美文网首页
文字处理之复制粘贴

文字处理之复制粘贴

作者: Geniusn | 来源:发表于2017-11-22 01:02 被阅读0次

    代码

    - (void)viewDidLoad {

        [super viewDidLoad];

        [self createLabel];

    }

    - (void)createLabel {

        self.testLabel = [[UILabel alloc]            initWithFrame:CGRectMake(20, 200, 200, 20)];

        self.testLabel.backgroundColor = [UIColor yellowColor];

        self.testLabel.text = @"据说这是马化腾亲自敲的";

        self.testLabel.userInteractionEnabled = YES;

        UILongPressGestureRecognizer *longTap = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longTapClick:)];

        [self.testLabel addGestureRecognizer:longTap];

        [self.view addSubview:self.testLabel];

    }

    //允许弹出菜单

    - (BOOL)canBecomeFirstResponder{

        return YES;

    }

    //设置可弹出的菜单

    - (BOOL)canPerformAction:(SEL)action withSender:(id)sender{

    if (action == @selector(copyContent:){

            //自定义的

            return YES;

    }else if (action == @selector(cut:) || action == @selector(copy:) || action == @selector(paste:)){   

            //系统的,默认返回NO

            return YES;

    }

        return [super canPerformAction:action withSender:sender];

    }

    // 长按弹出菜单并添加自定义菜单。

    - (void)longTapClick:(UILongPressGestureRecognizer *)recognizer{

        [self becomeFirstResponder];

        UIMenuItem *copyLink = [[UIMenuItem alloc] initWithTitle:@"复制" action:@selector(copyContent:)];

        [UIMenuController sharedMenuController].menuItems = @[copyLink];

        [[UIMenuController sharedMenuController] setTargetRect:self.testLabel.frame inView:self.testLabel.superview];

        [[UIMenuController sharedMenuController] setMenuVisible:YES animated:YES];

    }

    //自定义方法实现

    - (void)copyContent:(id)sender{

        UIPasteboard *pasteBoard = [UIPasteboard generalPasteboard];

        pasteBoard.string = self.testLabel.text;

    }

    //系统三方法实现

    - (void)cut:(UIMenuController *)menu {

        //剪切

        [self copy:menu];

        self.testLabel.text = nil;

    }

    - (void)copy:(UIMenuController *)menu {

        // 复制

        UIPasteboard *board = [UIPasteboard generalPasteboard];

        board.string = self.testLabel.text;

    }

    - (void)paste:(UIMenuController *)menu {

        // 粘贴

        UIPasteboard *board = [UIPasteboard generalPasteboard];

        self.testLabel.text = board.string;

    }

    效果图

    - end -

    相关文章

      网友评论

          本文标题:文字处理之复制粘贴

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