i have tableview with custom cell.the table is divided in many section and rows.i have a custom button on cell. now i want to get section number and row number when i click on that button.? any idea regarding this
You'll need to implement a UIControl event-handling method on your view controller, and set that as the handler for all your buttons. i.e. inside your -tableView:cellForRowAtIndexPath:
function you would do something like:
[theCell.button addTarget: self
action: @selector(buttonPressed:withEvent:)
forControlEvents: UIControlEventTouchUpInside];
Then your event handler would look like this:
- (void) buttonPressed: (id) sender withEvent: (UIEvent *) event
{
UITouch * touch = [[event touches] anyObject];
CGPoint location = [touch locationInView: self.tableView];
NSIndexPath * indexPath = [self.tableView indexPathForRowAtPoint: location];
/* indexPath contains the index of the row containing the button */
/* do whatever it is you need to do with the row data now */
}
A few thoughts:
You can iterate through the button's superview hierarchy until you find a UITableViewCell, then call - (NSIndexPath *)indexPathForCell:(UITableViewCell *)cell on the UITableView.
- (void)buttonClicked:(id)sender {
UIView *button = sender;
for (UIView *parent = [button superview]; parent != nil; parent = [parent superview]) {
if ([parent isKindOfClass: [UITableViewCell class]]) {
UITableViewCell *cell = (UITableViewCell *) parent;
NSIndexPath *path = [self.tableView indexPathForCell: cell];
// now use the index path
break; // for
}
}
}
You can alternately use the tag of the button to store an index referencing the row. This only holds a single integer, so it makes the most sense when you have a single section, or when you are managing your rows as a flat list.
You can alternately subclass UITableViewCell to encapsulate the button. Your UITableViewCell could respond to the button events and rebroadcast an event to its own delegate, passing self. The event delegate can then call - (NSIndexPath *)indexPathForCell:(UITableViewCell *)cell on the UITableView to get the index path.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With