C.Johns C.Johns - 2 months ago 6
iOS Question

how to set accessoryType when cell has been selected

I have been trying to figure out how to set the accessoryType to UITableViewCellAccessoryCheckmark when the cell is selected but am having trouble finding a decent example of this.

If you know how to do this or a good tutorial could you please let me know that would be great.

Answer

To restrict the user to just one selection, meaning to create an exclusive list of one choice only, you could follow these steps;

Firstly, have a global index path declared in your .h file to keep track of the already selected cell ->

NSIndexPath *oldIndexPath;

When you create the cells, be sure to set the accessory type to none, so that no cell is selected by default when the table is seen;

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CellIdentifier"];

    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"CallIdentifier"];
        cell.accessoryType = UITableViewCellAccessoryNone;      
    }
    return cell; 
}

Finally, in the didSelectRowAtIndexPath delegate method, add the following code which will remove the checkmark from the already selected cell, and add a checkmark to the newly selected one.

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];

    if (oldIndexPath==nil) { // No selection made yet
        oldIndexPath=indexPath;
        [cell setAccessoryType:UITableViewCellAccessoryCheckmark];
    }
    else {
        UITableViewCell *formerSelectedcell = [tableView cellForRowAtIndexPath:oldIndexPath]; // finding the already selected cell
        [formerSelectedcell setAccessoryType:UITableViewCellAccessoryNone];

        [cell setAccessoryType:UITableViewCellAccessoryCheckmark]; // 'select' the new cell
        oldIndexPath=indexPath;
    }   
}

Hope this works out! :)