ios開發之實現長按UITableViewCell彈出UIMenuController

來源:互聯網
上載者:User

項目中需要這個功能,網上找了下資料,有的說得不是很清楚,走了很多彎路才實現了,下面是實現步驟:

1.給cell添加UILongPressGestureRecognizer和相應處理事件

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath
*)indexPath

{    

   ..............

   UILongPressGestureRecognizer * longPressGesture =         [[UILongPressGestureRecognizer alloc]initWithTarget:selfaction:@selector(cellLongPress:)];

   [cell addGestureRecognizer:longPressGesture];

   return cell;

}

2.配置和顯示UIMenuController

- (void)cellLongPress UIGestureRecognizer *)recognizer{ 
 

    if (recognizer.state ==
UIGestureRecognizerStateBegan) {

       
CGPoint location = [recognizer
locationInView:self];

       
NSIndexPath * indexPath = [self
indexPathForRowAtPoint:location]; 

        UIMyTableViewCell *cell = (UIMyTableViewCell *)recognizer.view;

     //這裡把cell做為第一響應(cell預設是無法成為responder,需要重寫canBecomeFirstResponder方法)

        [cell becomeFirstResponder];

        

       
UIMenuItem *itCopy = [[UIMenuItem
alloc] initWithTitle:@"複製"
action:@selector(handleCopyCell:)];

       
UIMenuItem *itDelete = [[UIMenuItem
alloc] initWithTitle:@"刪除"
action:@selector(handleDeleteCell:)];        

        UIMenuController *menu = [UIMenuController
sharedMenuController];

[menu setMenuItems:[NSArray arrayWithObjects:itCopy,
itDelete,  nil]];

        [menu
setTargetRect:cell.frame inView:self];

        [menu setMenuVisible:YES
animated:YES];

        

        [itCopy release];

        [itDelete release];

    }

}

- (void)handleCopyCell:(id)sender{//複製cell

    NSLog(@"handle copy cell");

}

- (void)handleDeleteCell:(id)sender{//刪除cell

    NSLog(@"handle delete cell");

}

3.在自訂的cell裡重寫canBecomeFirstResponder方法,返回yes

//為了讓菜單顯示,目標視圖必須在responder鏈中,很多UIKit視圖預設並無法成為一個responder,因此你需要使這些視圖重載 canBecomeFirstResponder方法,並返回YES

- (BOOL)canBecomeFirstResponder{

    return
YES;

}


經過這幾步,就可以成功顯示了,又在網上看到一篇講這個的外文,分享一下:

http://www.intridea.com/blog/2010/12/22/developers-notes-for-uimenucontroller


相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.