search

Home  >  Q&A  >  body text

objective-c - 自定义cell上的button监听的问题,用indexPathForSelectedRow取值问题

我用 xib 自定义 cell 前面有个 button,写 cell 中监听 button,点击后发送通知到 tableView 修改数据,在通知方法中用 indexPathForSelectRow.row 拿到当前模型数据,但 indexPathForSelectRow.row 返回值一直为 0。

#pragma mark - 接受通知的方法
- (void)deleteBtnClick:(NSNotification *)note
{
    NSLog(@"%ld" ,self.searchResult.indexPathForSelectedRow.row);
}
習慣沉默習慣沉默2758 days ago752

reply all(2)I'll reply

  • 黄舟

    黄舟2017-05-02 09:23:53

    How much do you expect it to be? Is it the cell where you clicked the button? What you get here is the currently selected row. If you click a button in that cell, that cell may not be selected. You can try adding the row of the clicked row in the userInfo of the notification. Or in fact, there is no need to go through such trouble. It would be easier to use block to handle such things.

    @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
        }];
    }
    
    

    reply
    0
  • 怪我咯

    怪我咯2017-05-02 09:23:53

    @Unsolved

    You need to click the delete button on the right to delete the data corresponding to the cell in the history record, so you need to get the row of the cell. I originally planned to bind the tab of the delete button, but the printed tag is always 0 (I don’t know if it is because the cell uses xib Customized),
    Finally, I customized a UIbutton with num attribute. In cellForRowAtIndexPath, I passed the indexpath.row value to the num attribute of the delete button. When the listening button was clicked, I sent a value notification containing num to the tableviewcontroller just now, and then deleted the model data. The corresponding value in .
    This can solve the problem, but it seems not good to pass it around like this. Is there a better way??

    reply
    0
  • Cancelreply