陈斌彬的技术博客

Stay foolish,stay hungry

自定义剪贴板的使用

其实自定义剪贴板也非常简单,无非是放开响应时间,通过UIMenuController自定义剪贴板,然后就是最关键的实现你所用的copy方法拉。 为了方便实用,我给cell添加了长按事件,看代码—

UILongPressGestureRecognizer *recognizer = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPress:)];
    [cell addGestureRecognizer:recognizer];

好,事件加上了,剩下的点击就是实现自定义剪贴板了,上代码:

- (void)longPress:(UILongPressGestureRecognizer *)recognizer{
   if (recognizer.state == UIGestureRecognizerStateBegan) {
         CopyCell *cell = (CopyCell *)recognizer.view;
         [cell becomeFirstResponder];
        UIMenuItem *flag = [[UIMenuItem alloc] initWithTitle:@"Flag"action:@selector(flag:)];
        UIMenuItem *approve = [[UIMenuItem alloc] initWithTitle:@"Approve"action:@selector(approve:)];
        UIMenuItem *deny = [[UIMenuItem alloc] initWithTitle:@"Deny"action:@selector(deny:)];
        UIMenuController *menu = [UIMenuController sharedMenuController];

    [menu setMenuItems:[NSArray arrayWithObjects:flag, approve, deny, nil]];

    NSLog(@".....%@",NSStringFromCGRect(cell.frame));
    [menu setTargetRect:cell.frame inView:cell.superview];

    [menu setMenuVisible:YES animated:YES];
  }
}

通过上面这段代码,自定义剪贴板成功搞定,运行,你猛然会发现,操,怎么剪贴板没有出来,我猜你已经想到为什么了,因为

- (BOOL)canBecomeFirstResponder{
    return YES;
}

这么重要的一句话没有加,OK,下面就是你所要使用的方法了

- (void)flag:(id)sender {

    NSLog(@"Cell was flagged");

}
- (void)approve:(id)sender {

    NSLog(@"Cell was approved");
}

- (void)deny:(id)sender {

    NSLog(@"Cell was denied");

}

好,这就是基本的剪贴板的自定义使用了,为了更直观,上述三篇文章均由下面相似的效果图一张

img