Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a UITableViewCell with a UISwitch and get the data?

I have a simple problem. I created a custom UITableViewCell that includes a UISwitch in Interface Builder.

Question 1: Easier, better way to do it ? Question 2: When used in an UITableViewController, what would be the best way to get the data ? At some point I either need to go through the table and check every cell about the status OR send some feedback when the status of the switches changes directly ?

Thanks for the help.

like image 270
eemceebee Avatar asked Jan 03 '11 15:01

eemceebee


People also ask

How do you create a table view cell subclass?

The same way that you create a UIViewController or UITableViewController : In your project, go to New File. Select Cocoa Touch Class under iOS. The subclass is UITableViewCell and the name is whatever name you're giving it. Within that class, you drag your buttons, labels, etc to create your outlets.


2 Answers

You could just add the UISwitch in your accessory view. That is the easiest way to do it, not to mention that it looks 'elegant'.

Then, in your tableview controller code, you could just call a selector every time the switch is toggled, or even toggle the switch itself by getting the switch's current status in your controller.

Let know if you'd like a code sample.

---sample code---

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {  static NSString *CellIdentifier = @"Cell";  UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; if (cell == nil) {     cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];     //add a switch     UISwitch *switchview = [[UISwitch alloc] initWithFrame:CGRectZero];     cell.accessoryView = switchview;     [switchview release]; }  cell.textLabel.text = [NSString stringWithFormat:@"%d", indexPath.row];  return cell; } 

Then, you could have a method that updates a switch based on changes in your model. You could use anything you want - delegates, notifications, KVO, etc.

Example:

- (void)updateSwitchAtIndexPath:(NSIndexPath *)indexPath { UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:indexPath]; UISwitch *switchView = (UISwitch *)cell.accessoryView;  if ([switchView isOn]) {     [switchView setOn:NO animated:YES]; } else {     [switchView setOn:YES animated:YES]; }   } 
like image 79
Saurabh G Avatar answered Oct 04 '22 15:10

Saurabh G


Switch.tag = indexPath.row;
[Switch addTarget:self action:@selector(updateSwitchAtIndexPath:) forControlEvents:UIControlEventTouchUpInside];



- (void)updateSwitchAtIndexPath:(UISwitch *)aswitch{
    FFLog(@"%i",aswitch.tag);
}
like image 34
wang.qingyi Avatar answered Oct 04 '22 15:10

wang.qingyi