新手,勿噴~
----------------------------------------------------------------------------------------------------------------------------------------------------------------
最近這幾天做了一個長按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。
新聞熱點
疑難解答