简体   繁体   中英

UITableViewCellAccessoryCheckmark on click of cell

I have a UITableView with each cell is having a UITableViewCellAccessoryCheckmark. The user can check and uncheck the cells depending on his preference. The user can check/select multiple cells in the tableview. A selected/checked cell can be unchecked and rechecked again on user preference. This is what I have tried.

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
if([[NSIndexPath indexPathWithIndex:indexPath.row] isEqual:self.selectedIndex]){
                    if(cell.accessoryType == UITableViewCellAccessoryCheckmark)
                        cell.accessoryType = UITableViewCellAccessoryNone;
                    else
                        cell.accessoryType = UITableViewCellAccessoryCheckmark;
                }
                else{
                    if(cell.accessoryType == UITableViewCellAccessoryCheckmark){

                    }
                    else{
                        cell.accessoryType = UITableViewCellAccessoryNone;}
                }
}

I am not getting the logic right in this case. The above is the closest I have come, but again, the first time tableview loads every cell is checked. But the rest of the features are OK.

So what I want is, initially when the view is loaded, I have to have all cells in the UITableView unchecked. Then depending on the selection of the cells, the checkmark has to be updated in each cell. The property selectedIndex is of type NSIndexPath and is updated each time in didSelectRowAtIndexpath .

Never check your selected state based on any data from cell, always have your own data model or array to maintain the selected states.

eh, Why? O_o

Well Typically UITableViewCell are re-used, the cell appeared at index 1 may appear again with same state at index 8 or 7 or 9 or whatever index (that We don't need to know typically ) When you are using dequeueReusableCell:

If you want to have CheckBox style (Multiple Selection), you need to have an Array to map selected indices.

If you want to have RadioButton style (Single selection at a time), you need to have single variable referencing to the selected index.

In your particular case from your code.. this can be solved like this:

if([[NSIndexPath indexPathWithIndex:indexPath.row] isEqual:self.selectedIndex]){
      cell.accessoryType = UITableViewCellAccessoryCheckmark;
else{
      cell.accessoryType = UITableViewCellAccessoryNone;}
}

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