How to know the UITableview row number

前端 未结 10 1840
粉色の甜心
粉色の甜心 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:53

    The accepted answer on this post is perfectly fine. I'd like to suggest to readers that the following, derived from @robmayoff on this post, is also perfectly fine:

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

    Some have asserted that this approach contains too much computational work because of the while loop. The alternative, convert the view's origin to table view coordinate space and call indexPathForRowAtPoint:, hides even more work.

    Some have asserted that this approach is unsafe relative to potential SDK changes. In fact, Apple has already changed the tableview cell hierarchy once, adding a contentView to the cell. This approach works before and after such a change. As long as view ancestors can be found via a chain of superviews (which is as fundamental as anything in UIKit), this is good code.

提交回复
热议问题