I'm making a settings page, and want the very first row of the first section to have a UISwitch. I've achieved this using the following code:
// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier];
}
if (indexPath.section == 0){
[[cell textLabel] setText:[table1labels objectAtIndex:indexPath.row]];
if (indexPath.row == 0 && indexPath.section == 0){
UISwitch *switchview = [[UISwitch alloc] initWithFrame:CGRectZero];
cell.accessoryView = switchview;
}else{
[[cell detailTextLabel] setText:@"test"];
}
}else{
[[cell textLabel] setText:[table2labels objectAtIndex:indexPath.row]];
[[cell detailTextLabel] setText:@"test"];
}
return cell;
}
When the page loads, the first row in the first section has a UISwitch, and all others say "test". However, when I scroll on the page, more UISwitches appear randomly. They do not replace the text "test", but just push it to the left. It does not happen on every one of them. Just randomly when a cell leaves the view and comes back into the view. Can anyone tell me how to fix this?
I've only tested it on the 5.1 simulator. Not on an actual device yet. Could this just be a simulator issue?
You keep reusing the very same cell, that is the important part of your issue.
Now assume a cell that was initially used for your UISwitch is reused for an index that is not equal to the one you want to show it in. For that case, you will have to manually hide or replace the UISwitch.
As an alternative, I would strongly suggest you to use different cell identifiers for the cells that actually do not look alike.
// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *cellIdentifier;
if (indexPath.row == 0 && indexPath.section == 0)
{
cellIdentifier = @"CellWithSwitch";
}
else
{
cellIdentifier = @"PlainCell";
}
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:cellIdentifier];
}
if (indexPath.section == 0)
{
[[cell textLabel] setText:[table1labels objectAtIndex:indexPath.row]];
if (indexPath.row == 0 && indexPath.section == 0)
{
UISwitch *switchview = [[UISwitch alloc] initWithFrame:CGRectZero];
cell.accessoryView = switchview;
}
else
{
[[cell detailTextLabel] setText:@"test"];
}
}else{
[[cell textLabel] setText:[table2labels objectAtIndex:indexPath.row]];
[[cell detailTextLabel] setText:@"test"];
}
return cell;
}