UISwitch in UITableView cell

How can I insert a UISwitch into a UITableView cell? Examples can be seen in the settings menu.

My current solution:

 UISwitch *mySwitch = [[[UISwitch alloc] init] autorelease]; cell.accessoryView = mySwitch; 
+72
objective-c iphone cocoa-touch uitableview uiswitch
Sep 22 2018-10-22
source share
4 answers

Install it, since an accessory is usually the way to go. You can configure it in tableView:cellForRowAtIndexPath: You can use the target / action to do something when the switch is turned upside down. For example:

 - (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 release]; } return aCell; } break; } return nil; } - (void)switchChanged:(id)sender { UISwitch *switchControl = sender; NSLog( @"The switch is %@", switchControl.on ? @"ON" : @"OFF" ); } 
+182
Sep 22 '10 at 20:57
source share

You can add UISwitch or any other control to the accessoryView cell. Thus, it will appear on the right side of the cell, which is probably what you need.

+10
Sep 22 '10 at 14:11
source share
 if (indexPath.row == 0) {//If you want UISwitch on particular row UISwitch *theSwitch = [[UISwitch alloc] initWithFrame:CGRectZero]; [cell addSubview:theSwitch]; cell.accessoryView = theSwitch; } 
+8
Sep 22 '10 at 14:34
source share

You can prepare the cell in Interfacebuilder, associate it with the IBOutlet of your Viewcontroller, and return it when the tableview asks for the correct row.

Instead, you can create a separate xib for the cell (again with IB) and load it with UINib when creating the cells.

Finally, you can create the switch programmatically and add it to your content content content or content.

Which one suits you best depends a lot on what you like to do. If your table contents are fixed (for the settings page, etc.), the first two may work well, if the content is dynamic, I would prefer a software solution. Please be more specific in what you would like to do, this would facilitate the answer to your question.

+2
Sep 22 '10 at 14:13
source share



All Articles