UIMenuController 聊天時的復(fù)制、刪除、撤回

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


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

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

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

讓后我們來實現(xiàn)這個longPress:方法:

- (void)longPress:(UILongPressGestureRecognizer *)longRecognizer {
    if (longRecognizer.state == UIGestureRecognizerStateBegan) {
        [view becomeFirstResponder];
        UIMenuController *menu = [UIMenuController sharedMenuController];
        UIMenuItem *copyItem = [[UIMenuItem alloc] initWithTitle:@"復(fù)制" 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并沒有出現(xiàn)!還要加點幾行。

#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 實現(xiàn)成為第一響應(yīng)者方法
- (BOOL)canBecomeFirstResponder {
    return YES;
}

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

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

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

OK,現(xiàn)在復(fù)制、刪除的功能基本實現(xiàn)了。你可以在自己的工程中試試了。

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

推薦閱讀更多精彩內(nèi)容