逼哥的成长之路 - 怎样获取正确的Cell对应的Row

2017-11-02  本文已影响23人  Jack_Dou

由于Cell的自定义 想必大家一定会遇到 “展示更多或者删除等按钮”的自定义控件

由于本人项目中俩者皆有(删除使用的是tableView的代理方法)故而遇到的问题分享给大家

当用户点击“更多”按钮时改变Cell的高度或其他操作(这里是model控制的按钮打开与关闭)这时候需要知道用户点击的是哪一行Cell 

刚开始的错误做法:(这里我是在自定义Cell里面定义了NSIndexPath属性,然后通过block把对应的indexPath传递出来)

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

static NSString *identifier = @"AdminCell";

AdminCell  *cell = (AdminCell *)[tableView dequeueReusableCellWithIdentifier:identifier];

if (nil == cell) {

cell = [[AdminCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];

}

cell.indexPath = indexPath;

cell.reloadTab = ^(NSIndexPath *indexPath) {

AdminModel *tempModel = self.sourceArray[indexPath.row];

tempModel.isMore = !tempModel.isMore;

[weakSelf.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];

};

}

这样实现当没有更改tableView的数据源时(tableView的行数不变时)不会有任何问题,但是当数据源改变时(tableView的行数改变)就会崩溃了,崩溃原因其实是返回的indexpath的不正确造成的!!!

正确做法:

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

static NSString *identifier = @"AdminCell";

AdminCell  *cell = (AdminCell *)[tableView dequeueReusableCellWithIdentifier:identifier];

if (nil == cell) {

cell = [[AdminCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];

}

/**/把实际点击的按钮回调出来

cell.reloadTab = ^(UIButton *selectedBtn) {

/**/这行代码是准确的找到用户点击的按钮属于哪一行Cell

UITableViewCell *cell = (UITableViewCell *)selectedBtn.superview.superview;

/**/根据Cell得出NSIndexPath间接得到Row

NSIndexPath *selectedPath = [weakSelf.tableView indexPathForCell:cell];

AdminModel *tempModel = self.sourceArray[selectedPath.row];

tempModel.isMore = !tempModel.isMore;

[weakSelf.tableView reloadRowsAtIndexPaths:@[selectedPath] withRowAnimation:UITableViewRowAnimationFade];

};

}

上一篇 下一篇

猜你喜欢

热点阅读