Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UISwitch in a UITableView cell

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

My current solution:

UISwitch *mySwitch = [[[UISwitch alloc] init] autorelease]; cell.accessoryView = mySwitch; 
like image 587
testing Avatar asked Sep 22 '10 14:09

testing


People also ask

How can we use a reusable cell in UITableView?

For performance reasons, a table view's data source should generally reuse UITableViewCell objects when it assigns cells to rows in its tableView(_:cellForRowAt:) method. A table view maintains a queue or list of UITableViewCell objects that the data source has marked for reuse.

How do you perform a segue in a Tableview cell?

So, select the first view controller, and then go to the top menu and click on Editor → Embed In → Navigation Controller. For this, we are going to select the “show” segue in the “Selection Segue” section. This means that when you tap on the cell, it will cause this segue to happen.

What is a UITableView?

UITableView manages the basic appearance of the table, but your app provides the cells ( UITableViewCell objects) that display the actual content. The standard cell configurations display a simple combination of text and images, but you can define custom cells that display any content you want.


1 Answers

Setting it as the accessoryView is usually the way to go. You can set it up in tableView:cellForRowAtIndexPath: You may want to use target/action to do something when the switch is flipped. Like so:

- (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" ); } 
like image 131
zpasternack Avatar answered Sep 17 '22 04:09

zpasternack