長按Cell進行選擇,Cell進行選擇

來源:互聯網
上載者:User

長按Cell進行選擇,Cell進行選擇

新手,勿噴~

----------------------------------------------------------------------------------------------------------------------------------------------------------------

最近這幾天做了一個長按Cell刪除的功能。

添加了一個UILongPressGestureRecognizer長按手勢,在手勢的方法裡,直接寫

if (sender.state == UIGestureRecognizerStateBegan) {

}
然而再這個時候遇到了問題,我用下邊的辦法找到了cell的indexPath

 CGPoint point = [sender locationInView:self.tableView];
 NSIndexPath * indexPath = [self.tableView indexPathForRowAtPoint:point];

問題來了,平時我都是執行個體化一個cell,然後用indexPath.section和indexPath.row來確定不同位置的cell,給其載入資料。但是現在我只知道indexPath,怎麼才能找到它所對應的cell。額,難倒了我這個初學者,第一次遇到這種問題。後來看到了- (NSArray *)visibleCells;  這個方法是用來擷取螢幕上顯示的所有cell.

So happy,通過indexPath.row擷取cell,終於搞定。

NSArray *cells = [self.tableView visibleCells];
MapTableViewCell *cell = cells[indexPath.row];

前幾個cell沒有任何問題。然而當表示圖開始滾動以後,再選擇cell,就遭遇了各種崩潰。糾結了很久,發現崩潰的原因很簡單,數組越界。因為indexPath是遞增的,而cell的個數是固定的,自然而然,indexPath.row大於cell.count了。解決辦法很easy,cell.tag = indexPath.row; 找到癥結,解決麻煩!

 if (sender.state == UIGestureRecognizerStateBegan) {
        CGPoint point = [sender locationInView:self.tableView];
        NSIndexPath * indexPath = [self.tableView indexPathForRowAtPoint:point];
        if(indexPath == nil) return ;
        
        NSArray *cells = [self.tableView visibleCells];
        NSInteger tag = ((UITableViewCell *)[cells firstObject]).tag;
        UITableViewCell *cell = cells[indexPath.row - tag];
    }
最後的結果就變成了這個樣子,我拿到了長按手勢點擊的cell。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.