UIMenuController 聊天時的復制、刪除、撤回

![Uploading 屏幕快照 2016-11-08 下午12.35.00_719577.png . . .]


屏幕快照 2016-11-08 下午12.35.00.png

喏,就是這個小東西,聊天的時候我們都用到了,實際開發中好像不太常用。它叫做UIMenuController,下面分享它的使用。
一般是在長按的時候會出現這個小菜單,那么就需要在長安出現菜單的控件上加一個手勢:

[view addGestureRecognizer:[[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPress:)]];

讓后我們來實現這個longPress:方法:

- (void)longPress:(UILongPressGestureRecognizer *)longRecognizer {
    if (longRecognizer.state == UIGestureRecognizerStateBegan) {
        [view becomeFirstResponder];
        UIMenuController *menu = [UIMenuController sharedMenuController];
        UIMenuItem *copyItem = [[UIMenuItem alloc] initWithTitle:@"復制" action:@selector(copyItemClicked:)];
        UIMenuItem *deleteItem = [[UIMenuItem alloc] initWithTitle:@"刪除" action:@selector(deleteItemClicked:)];
        [menu setMenuItems:[NSArray arrayWithObjects:copyItem, deleteItem, nil]];
        CGRect rect = view.bounds;
        rect.origin.y = rect.origin.y - SCALE6P(10);
        rect.size.height = rect.size.height + SCALE6P(20);
        [menu setTargetRect:rect inView:view];
        [menu setMenuVisible:YES animated:YES];
    }
}

寫好這些以后,長按那個 view ,UIMenuController并沒有出現!還要加點幾行。

#pragma mark 處理action事件
- (BOOL)canPerformAction:(SEL)action withSender:(id)sender {
    if (action == @selector(copyItemClicked:)) {
        return YES;
    } else if (action == @selector(deleteItemClicked:)){
        return YES;
    }
    return [super canPerformAction:action withSender:sender];
}

#pragma mark 實現成為第一響應者方法
- (BOOL)canBecomeFirstResponder {
    return YES;
}

讓添加了UIMenuController的view響應才可以出現那個小黑框,但是點擊復制和刪除當然就沒什么作用了。要實現@selector(copyItemClicked:)和@selector(deleteItemClicked:)方法才行啊!

- (void)deleteItemClicked:(id)sender {
    NSLog(@"刪除");
   // 做刪除,一般是tableView中刪除某一行,不要忘記刪除數據源在reload data 就好了。
        NSIndexPath *indexPath ; // 計算你的tableView的indexPath
        [self.list removeObjectAtIndex:indexPath.row];
        [self.tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
}

- (void)copyItemClicked:(id)sender {
    NSLog(@"復制");
    UIPasteboard *pasteBoard = [UIPasteboard generalPasteboard];
    pasteBoard.string = youView.text;
}

OK,現在復制、刪除的功能基本實現了。你可以在自己的工程中試試了。

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容