简体   繁体   中英

UITableViewCell Accessory Repeating?

In my app, I have a detailed view where the user can edit attributes of for example a person, their name, address etc.

In two cells, rather than being able to select them to edit their contents, they have a right accessory, a UISwitch, however sometimes, its inconsistent, but they replicate onto other cells in my last section.

I have been scanning my code dozens of times over with a fine comb and can't find the damn cause. What might cause this? Here is the code that I use to create the UISwitch on just a single cell:

if (indexPath.section == 0 && indexPath.row == 1) 
{
    cell.textLabel.text = @"Confirmed";

    //Make the cell unselectable
    [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
    //Create and add uiswitch
    confirmedSwitch = [[UISwitch alloc] initWithFrame:CGRectZero];
    [confirmedSwitch addTarget:self action:@selector(switchConfirmedStatus:) forControlEvents:UIControlEventValueChanged];
    [confirmedSwitch setOn:[venue.isConfirmed boolValue]];
    cell.accessoryView = confirmedSwitch;
}

So you expect it to only show up on that cell, see anything odd with that code? I have checked my if statements and all my brackets indexPath checks are correct.

Anyone see this before or have any clues?

The problem is because of reusability issues in the UITableView . You probably use the same identifier for all cells and this causes the cellForRowAtIndexPath to be implemented in other rows (when you scroll up and down).

This is a common problem when you are developing applications with tableView and there are plenty of questions like this on StackOverflow.

As a general solution, you will need to do either of these.

  1. Use different identifiers when you assign dequeueReusableCellWithIdentifier for each cell. This is fairly simple, and you just need to assign different identifiers for them.

  2. Subclass you UITableViewController , and create your own CustomTableViewController which will implement the necessary components in the cell . I believe you will need to override the set Layout Subviews method.

Take a array in view will appear and add object 0 for this row and 1 for all other rows and then in cellForRowAtIndexPath check if array has 0 at that index if it has then put switch otherwise nill..

for(int i =0;i<10;i++)
{
    if(i==1)
    {
        [arrayForSwitch addObject:@"0"];
    }
    else
    {
        [arrayForSwitch addObject:@"1"];
    }
}

then in cellForRowAtIndexPath write condition

if([arrayForSwitch objectAtIndex:indexPath.row isEqualToString:@"0"])
{
    cell.accessoryView = confirmedSwitch;
}
else
{

    cell.accessoryView =UITableViewCellAccessoryNone;
}

it will now remain same

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM