Accessing the Row of a UISwitch in a UITableView
I Used Code Similar to This to add switches to the rows of my TableView. Once the switch is changed it calls switchChanged. But How do I access what row (which switch) was actually changed?
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
switch( [indexPath row] ) {
case MY_SWITCH_CELL: {
UITableViewCell* aCell = [tableView dequeueReusableCellWithIdentifier:@"SwitchCell"];
if( aCell == nil ) {
aCell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:@"SwitchCell"] autorelease];
aCell.textLabel.text = @"I Have A Switch";
aCell.selectionStyle = UITableViewCellSelectionStyleNone;
UISwitch *switchView = [[UISwitch alloc] initWithFrame:CGRectZero];
aCell.accessoryView = switchView;
[switchView setOn:NO animated:NO];
[switchView addTarget:self action:@selector(switchChanged:) forControlEvents:UIControlEventValueChanged];
[switchView re开发者_StackOverflow社区lease];
}
return aCell;
}
break;
}
return nil;
}
- (void) switchChanged:(id)sender {
UISwitch* switchControl = sender;
NSLog( @"The switch is %@" switchControl.on ? @"ON" : @"OFF );
}
The UITableViewCell
object that you are adding the switch to will be switchControl.superview
so
UITableViewCell * cell = (UITableViewCell *)switchControl.superview;
NSIndexPath * indexPath = [self.tableView indexPathForCell:cell];
精彩评论