Select UITableView's row when clicking on UISwitch
ios, iphone, objective-c, xcode
Solution
To find the cell that holds the switch
UISwitch *switchInCell = (UISwitch *)sender;
UITableViewCell * cell = (UITableViewCell*) swithInCell.superview;
To find the indexpath of that cell
NSIndexPath * indexpath = [myTableView indexPathForCell:cell]
In your case
- (void) switchChanged:(id)sender {
UISwitch *switchInCell = (UISwitch *)sender;
UITableViewCell * cell = (UITableViewCell*) swithInCell.superview;
NSIndexPath * indexpath = [myTableView indexPathForCell:cell]
NSString *strCatID =[[NSString alloc]init];
strCatID = [self.catIDs objectAtIndex:indexpath];
NSLog( @"The switch for item %@ is %@",StrCatID, switchInCell.on ? @"ON" : @"OFF" );
}
Problem
I have a `UITableView` with `UISwitchs` on them. When the switch is toggled I want to run a function. The function just logs If the switch is on or off and the row that the switch has been changed on. The problem that im having is that when I click on the switch it does not log the correct row unless I have clicked on that row before clicking the switch. I guess my problem is that clicking the switch does not select the row. How can I make it so that it either selects the row or can I add the ID to the switch? So switch ID "1" is "ON". ``` - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{ static NSString *CellIdentifier = @"POICell"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath]; //set the cell text to the catName cell.textLabel.text = [self.catNames objectAtIndex:[indexPath row]]; //add switch cell.selectionStyle = UITableViewCellSelectionStyleNone; UISwitch *switchView = [[UISwitch alloc] initWithFrame:CGRectZero]; cell.accessoryView = switchView; [switchView setOn:YES animated:NO]; [switchView addTarget:self action:@selector(switchChanged: ) forControlEvents:UIControlEventValueChanged]; // Configure the cell... return cell; } - (void) switchChanged:(id)sender { NSString *StrCatID =[[NSString alloc]init]; StrCatID = [self.catIDs objectAtIndex:[self.inputTableView indexPathForSelectedRow].row]; UISwitch* switchControl = sender; NSLog( @"The switch for item %@ is %@",StrCatID, switchControl.on ? @"ON" : @"OFF" ); } ```