I added a UISwitch in a UITableViewCell, the table contents are dynamics, which means that there may be many UISwitches in a tableview, I need to get the UISwitch state for every UITableViewCell, but not getting the indexPath in accessoryButtonTappedForRowWithIndexPath method.
my code is:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
LocationCell *cell = (LocationCell *)[tableView
dequeueReusableCellWithIdentifier:@"LocationCell"];
UISwitch *useLocationSwitch = [[UISwitch alloc] initWithFrame:CGRectZero];
[cell addSubview:useLocationSwitch];
cell.accessoryView = useLocationSwitch;
[useLocationSwitch addTarget: self
action: @selector(accessoryButtonTapped:withEvent:)
forControlEvents: UIControlEventTouchUpInside];
return cell;
}
- (void) accessoryButtonTapped: (UIControl *) button withEvent: (UIEvent *) event
{
NSIndexPath * indexPath = [showLocationTableView indexPathForRowAtPoint: [[[event touchesForView: button] anyObject] locationInView: showLocationTableView]];
if ( indexPath == nil )
return;
[showLocationTableView.delegate tableView: showLocationTableView accessoryButtonTappedForRowWithIndexPath: indexPath];
}
-(void)tableView:(UITableView *)tableView accessoryButtonTappedForRowWithIndexPath:(NSIndexPath *)indexPath{
NSLog(@"index path: %@", indexPath.row);
}
The control event should be UIControlEventValueChanged.
Not UIControlEventTouchUpInside. Change that and try again.
So the action setting statement should be as follows:
[useLocationSwitch addTarget: self
action: @selector(accessoryButtonTapped:withEvent:)
forControlEvents: UIControlEventValueChanged];
Edit:
- (void) accessoryButtonTapped: (UIControl *) button withEvent: (UIEvent *) event
{
UISwitch *switch1 = (UISwitch *)button;
UITableViewCell *cell = (UITableViewCell *)switch1.superview;
NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
//NSIndexPath * indexPath = [showLocationTableView indexPathForRowAtPoint: [[[event touchesForView: button] anyObject] locationInView: showLocationTableView]];
if ( indexPath == nil )
return;
[showLocationTableView.delegate tableView: showLocationTableView accessoryButtonTappedForRowWithIndexPath: indexPath];
}
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