Not getting indexPath for UISwitch listening in UITableViewCell
I added UISwitch to UITableViewCell, table content is dynamic, which means there can be many UISwitches in table view, I need to get UISwitch state for each UITableViewCell, but not get indexPath
in accessoryButtonTappedForRowWithIndexPath
.
my code:
- (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);
}
+3
source to share
1 answer
Control event should be UIControlEventValueChanged
.
Not UIControlEventTouchUpInside
. Please change this and try again.
So, the instruction for setting actions 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];
}
+5
source to share