代码优化iOS 开发 iOS开发

cell中事件代理到tableView进行操作(如删除)的实现

2015-03-25  本文已影响1004人  大灰灰iOS

项目中有个需求,cell的删除按钮代理到tableView里实现并进行删除动画。

原来我的做法是,给cell加个属性cellIndex,然后在cell赋值的时候,将indexPath.row赋给cellIndex。

后来发现有个问题,就是我连续进行两次删除操作的时候,cell的cellIndex就会发生混乱。

所以改用以下方法,在cell中取到indexPath,代理出去使用,bug得到解决

//IOS7以后,cell的superView为UITableViewWrapperView
UITableView *tableView = (UITableView *)self.superview.superview;
NSIndexPath *indexPath = [tableView indexPathForCell:self];
//然后代理到tableView,执行:
[self.list removeObjectAtIndex:index];
[self.tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationTop];

下面拟将获取indexPath的方法封装在UITableViewCell中,方便使用:

@interface UITableViewCell (UnNuLL)
- (NSIndexPath *)getIndexPath;
@end
@implementation UITableViewCell (UnNuLL)

- (NSIndexPath *)getIndexPath
{
    //IOS7 OR LATER AVALIABLE
    UITableView *tableView = (UITableView *)self.superview.superview;
    return [tableView indexPathForCell:self];
}

@end

简书已经弃用,欢迎移步我的小专栏:
https://xiaozhuanlan.com/dahuihuiiOS

上一篇 下一篇

猜你喜欢

热点阅读