新手,勿噴~
----------------------------------------------------------------------------------------------------------------------------------------------------------------
最近這幾天做了一個長按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,給其加載數(shù)據(jù)。但是現(xiàn)在我只知道indexPath,怎么才能找到它所對應(yīng)的cell。額,難倒了我這個初學(xué)者,第一次遇到這種問題。后來看到了- (NSArray *)visibleCells; 這個方法是用來獲取屏幕上顯示的所有cell.
So happy,通過indexPath.row獲取cell,終于搞定。
NSArray *cells = [self.tableView visibleCells];
MapTableViewCell *cell = cells[indexPath.row];
前幾個cell沒有任何問題。然而當(dāng)表示圖開始滾動以后,再選擇cell,就遭遇了各種崩潰。糾結(jié)了很久,發(fā)現(xiàn)崩潰的原因很簡單,數(shù)組越界。因為indexPath是遞增的,而cell的個數(shù)是固定的,自然而然,indexPath.row大于cell.count了。解決辦法很easy,cell.tag = indexPath.row; 找到癥結(jié),解決麻煩!
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];
}
最后的結(jié)果就變成了這個樣子,我拿到了長按手勢點擊的cell。
新聞熱點
疑難解答