UISwitch's being added and removed into wrong and random cells?
Using the code bellow in my table view data source method (...cellForRowAtIndexPath:) I am creating UISwitch's in only certain cells for a user settings view that goes into a popover view.
The switch's are working however for some reason when I scroll up and down the view switch's are being added and removed from random cells that I did not specify should have a UISwitch in them.
What am I doing wrong here?
This is some of my code:
if (section == 0) {
if (row == 0) {
cell.textLabel.text = @"Units";
}
if (row == 1) {
cell.textLabel.text = @"Prefered System";
}
if (row == 2) {
cell.selectionStyle = UITableViewCellSelectionStyleNone;
cell.textLabel.text = @"Lock System";
UISwitch *switch1 = [[UISwitch alloc] initWithFrame:switchFrame];
if ([defaults boolForKey:kLockSystem]) {
[switch1 setOn:YES animated:NO];
}
else {
[switch1 setOn:NO animated:NO];
}
[switch1 addTarget:self action:@selector(switchToggled:) forControlEvents:UIControlEventValueChanged];
switch1.tag = 1;
cell.accessoryView = switch1;
[switch1 release];
}
if (row == 3) {
cell.selectionStyle = UITableViewCellSelectionStyleNone;
cell.textLabel.text = @"Reset On Exit";
UISwitch *switch2 = [[UISwitch alloc] initWithFrame:switchFrame];
if ([defaults boolForKey:kResetOnExit]) {
[switch2 setOn:YES animated:NO];
}
else {
[switch2 setOn:NO animated:NO];
}开发者_运维知识库
[switch2 addTarget:self action:@selector(switchToggled:) forControlEvents:UIControlEventValueChanged];
switch2.tag = 2;
cell.accessoryView = switch2;
[switch2 release];
}
}
I guess you're using dequeueReusableCellWithIdentifier:
to get a cell before executing that code. Your problem that the UISwitches are not removed from the cell before it gets returned by that method.
With the code you are using, there should be a simple fix: Just set cell.accessoryView
to nil for the rows that do not have a switch. Or set it nil unconditionally right after you get the cell, before you enter the posted bit of code.
精彩评论