How to know the UITableview row number

前端 未结 10 1842
粉色の甜心
粉色の甜心 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 12:04

    Tags, subclasses, or view hierarchy navigation are too much work!. Do this in your action method:

    CGPoint hitPoint = [sender convertPoint:CGPointZero toView:self.tableView]; 
    NSIndexPath *hitIndex = [self.tableView indexPathForRowAtPoint:hitPoint];
    

    Works with any type of view, multi section tables, whatever you can throw at it - as long as the origin of your sender is within the cell's frame (thanks rob!), which will usually be the case.

    And here it is in a UITableView Swift extension:

    extension UITableView {
        func indexPath(for view: UIView) -> IndexPath? {
            let location = view.convert(CGPoint.zero, to: self)
            return self.indexPathForRow(at: location)
        }
    }
    

提交回复
热议问题