I have UITableViewCell with UILabel and UISwitch. By default all UISwitch is set to off.
Once I will turn on the switch and then scroll through table the switch value is set to default again,i.e.Off
Below is the code which I have used:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if(cell != nil) cell = nil;
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
if (indexPath.row == 0) {
UILabel *lbl1 = [[UILabel alloc] initWithFrame:CGRectMake(20, 10, 100, 30)];
lbl1.text = @"Some Text";
[cell addSubview:lbl1];
switch = [[UISwitch alloc] initWithFrame:CGRectMake(190, 10, 200, 30)];
[switch setOn:NO];
switch.tag = 1;
[switch addTarget:self action:@selector(switchTapped:) forControlEvents:UIControlEventChanged];
[cell addSubview:switch];
}
}
// Below is my switchTapped method:
- (void) switchTapped: (id)sender {
UISwitch *tapSwitch = (UISwitch *)sender;
switch (tapSwitch.tag) {
case 1:
if (tapSwitch.on) {
// do something
}
else {
// do something
}
break;
case 2:
if (tapSwitch.on) {
// do something
}
else {
// do something
}
break;
}
Am I doing anything wrong over here?
Thank You.
You’re using really nasty code which regenerates the cell each time it’s needed:
Do you bind the state of your switch to some retained object (e.g. Item model object, where single cell reflects an Item)?