How to know the UITableview row number

前端 未结 10 1709
粉色の甜心
粉色の甜心 2020-11-22 11:28

I have a UITableViewCell with UISwitch as accessoryview of each cell. When I change the value of the switch in a cell, how can I know in which row

10条回答
  •  伪装坚强ぢ
    2020-11-22 11:49

    If you set the tag property to the row number (as suggested by other answers), you have to update it every time in tableView:cellForRowAtIndexPath: (because a cell can be reused for different rows).

    Instead, when you need the row number, you can walk up the superview chain from the UISwitch (or any other view) to the UITableViewCell, and then to the UITableView, and ask the table view for the index path of the cell:

    static NSIndexPath *indexPathForView(UIView *view) {
        while (view && ![view isKindOfClass:[UITableViewCell class]])
            view = view.superview;
        if (!view)
            return nil;
        UITableViewCell *cell = (UITableViewCell *)view;
        while (view && ![view isKindOfClass:[UITableView class]])
            view = view.superview;
        if (!view)
            return nil;
        UITableView *tableView = (UITableView *)view;
        return [tableView indexPathForCell:cell];
    }
    

    This doesn't require anything in tableView:cellForRowAtIndexPath:.

提交回复
热议问题