问题描述
我用 xib 自定义 cell 前面有个 button,写 cell 中监听 button,点击后发送通知到 tableView 修改数据,在通知方法中用 indexPathForSelectRow.row 拿到当前模型数据,但 indexPathForSelectRow.row 返回值一直为 0。
#pragma mark - 接受通知的方法- (void)deleteBtnClick:(NSNotification *)note{ NSLog(@'%ld' ,self.searchResult.indexPathForSelectedRow.row);}
问题解答
回答1:这里你期望它是多少呢?是你点击 button 的那个 cell 吗? 你在这里取的是当前选中行,点击了那个 cell 里的一个 button,未必就选中了那个 cell。你可以试试在通知的 userInfo 里带着被点那一行的 row。或者其实不用搞这么麻烦的,用 block 来处理这样的事情会更容易一些。
@interface CustomCell: UITableViewCell@property (nonatomic, copy) void (^onDeleteBtn)();@end@implempation CustomCell- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { CustomCell *cell = [tableView dequeueReusableCellWithIdentifier:@'CustomCellIdentifier']; [cell setOnDeleteBtn:^{// 这里执行删除 indexPath 数据源的操作,然后 reloadData }];}回答2:
@未解
需要实现点击右边那个删除按钮删除历史记录上对应cell的数据,所以要拿到cell的row,原来打算绑定删除按钮的tab,但打印tag一直为0(不知道是不是因为cell是用xib自定义),最后我自定义一个UIbutton,带num属性,在cellForRowAtIndexPath传indexpath.row值到删除按钮的num属性,在监听按钮点击然后发送含有num的值得通知到刚才的tableviewcontroller,再删除模型数据中对应的值.这样可以解决问题,但这样传来传去,好像不好,有没有更好的办法呢??