Search code examples
objective-ctableviewcheckmark

Default CellAccessory


How can I set first row of tableview checkmarked when the app started? I mean when I start app now, there are few rows in tableview and when I click on some of them its accessory change to checkmark. When click another one, the another one comes checkmarked and previous checkmark dissapears. So now I want first row of tableview to be checkmarked when app is started and then when I click another row it 'uncheckmark' and 'checkmark' new row etc...


Solution

  • Try the options suggested in these posts how to apply check mark on table view in iphone using objective c? or iPhone :UITableView CellAccessory Checkmark

    Basically you need to keep track of the checkmarks using say a dictionary or so. And In viewDidLoad or init method make the first cell as checked in the dictionary. While drawing cells, always check if the corresponding entry in the dictionary is checked or not and display check mark accordingly. When user taps on a cell, modify the value in dictionary to checked/unchecked.

    Update: Here is a sample code.

    In .h file declare a property as

    @property(nonatomic) NSInteger selectedRow;
    

    Then use the below code,

    - (void)viewDidLoad {
      //some code...
    
      self.selectedRow = 0; //if nothing should be selected for the first time, then make it as -1
      //create table and other things
    }
    
    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
        // create cell and other things here
    
        if (indexPath.row == self.selectedRow)
        {
            cell.accessoryType = UITableViewCellAccessoryCheckmark;
        } else {
            cell.accessoryType = UITableViewCellAccessoryNone;
        }
    
        return cell;
    }
    
    - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
        // some other code..
    
        if (indexPath.row != self.selectedRow) {
           self.selectedRow = indexPath.row;
        }
    
        [tableView reloadData];
    }