我正嘗試使用UIMenuController在表格單元格上執行自定義操作,UIMenuController通過該操作長時間按下觸發。如何在UIMenuController中的自定義操作中獲取點擊表格視圖單元格
我在UITableViewController的子類的viewDidLoad方法中註冊了UILongPressGestureRecognizer,並使用@selector(handleMyAction)添加了自定義項目。
- (void)viewDidLoad
{
[super viewDidLoad];
[self.refreshControl addTarget:self action:@selector(refreshView:) forControlEvents:UIControlEventValueChanged];
UILongPressGestureRecognizer *longPressGesture = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(handleLongPress:)];
longPressGesture.minimumPressDuration = .5;
longPressGesture.delegate = self;
[self.tableView addGestureRecognizer:longPressGesture];
}
-(void)handleLongPress:(UILongPressGestureRecognizer *)gestureRecognizer
{
if(gestureRecognizer.state == UIGestureRecognizerStateBegan)
{
CGPoint point = [gestureRecognizer locationInView:self.tableView];
NSIndexPath * indexPath = [self.tableView indexPathForRowAtPoint:point];
if(indexPath == nil) return ;
UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
UIMenuItem *it = [[UIMenuItem alloc] initWithTitle:@"My Action on this cell" action:@selector(handleMyAction:)];
UIMenuController *menu = [UIMenuController sharedMenuController];
[menu setMenuItems:[NSArray arrayWithObjects:it, nil]];
[menu setTargetRect:cell.frame inView:cell.superview];
[menu setMenuVisible:YES animated:YES];
[self becomeFirstResponder];
}
}
我也覆蓋
- (BOOL)canBecomeFirstResponder{
return YES;
}
當我在一個小區按與自定義項正確顯示上下文菜單。但是,問題是我該如何實現處理自定義操作的方法,這應該在分接單元上執行。
- (void)handleMyAction:(id)sender
{
NSLog(@"Action triggered, however need some way to refer the tapped cell");
}
因爲只有信息我可以在這個方法得到的是發送者,這是UIMenuController自我,但我不知道如何才能獲得細胞,在其菜單觸發,所以我可以做進一步的行動關於細胞本身。
有人能幫我嗎?
謝謝。 Hai
你的意思是在cellForRowAtIndexPath中,對嗎?即使我這樣做,菜單將觸發單元格,並且我的動作handleMyAction的處理程序將被調用,我們將在彈出菜單中選擇「我對這個單元格的操作」條目,但是,如何訪問handleMyAction函數中的單元格,因爲這個函數的唯一參數是發送者,所以它是UIMenuController。 – Hai
實際上,如果您將手勢識別器設置爲單元格,發件人是手勢識別器本身,而gestureRecognizer.view是單元格。 – valheru
起初我長按細胞和彈出菜單觸發,無論我設置手勢識別器在表視圖或表視圖的每個單元格上,發件人是識別器,我相信這是真的,如果識別器是正如你所建議的那樣,這個單元格是識別器。視圖將是單元格。但問題不在這裏。我確實需要訪問菜單條目的回調函數中的單元格,當我點擊彈出式菜單時。在這種情況下,回調函數的發送者始終是菜單本身。 – Hai