Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to know the UITableview row number

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 the switch is? I need the row number in the switch value changed event.

like image 304
Jean Paul Scott Avatar asked Feb 14 '12 09:02

Jean Paul Scott


People also ask

What is UITableView in Swift?

A view that presents data using rows in a single column. iOS 2.0+ iPadOS 2.0+ Mac Catalyst 13.1+ tvOS 9.0+

How do I populate UITableView?

There are two main base ways to populate a tableview. The more popular is through Interface Building, using a prototype cell UI object. The other is strictly through code when you don't need a prototype cell from Interface Builder.

Which method is used to allow moving of row in UITableView?

moveRow(at:to:) Moves the row at a specified location to a destination location.


1 Answers

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)     } } 
like image 53
jrturton Avatar answered Oct 01 '22 11:10

jrturton