Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iPhone :UITableView CellAccessory Checkmark

In iPhone App on click of table view cell I want to display Table view cell Accessory type Check mark for that on didSelectRowAtIndexPath i am writing code

if(indexPath.row ==0) { [tableView cellForRowAtIndexPath:indexPath].accessoryType=UITableViewCellAccessoryCheckmark;  } 

and displaying check marks.

but in my case i wnt to allow user to check only on cell at a time means if user select other row then that row should checked and previously checked should be unchecked

How can I achieve that?

like image 823
ios Avatar asked May 11 '11 06:05

ios


1 Answers

Keep track, in an instance variable, of which row is checked. When the user selects a new row, first uncheck the previously checked row, then check the new row and update the instance variable.

Here is more detail. First add a property to keep track of the currently checked row. It's easiest if this is an NSIndexPath.

@interface RootViewController : UITableViewController {     ...     NSIndexPath* checkedIndexPath;     ... }  ... @property (nonatomic, retain) NSIndexPath* checkedIndexPath; ...  @end 

In your cellForRowAtIndexPath add the following:

if([self.checkedIndexPath isEqual:indexPath]) {     cell.accessoryType = UITableViewCellAccessoryCheckmark; } else  {     cell.accessoryType = UITableViewCellAccessoryNone; } 

How you code your tableView:didSelectRowAtIndexPath: will depend on the behavior you want. If there always must be a row checked, that is, that if the user clicks on an already checked row use the following:

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {     // Uncheck the previous checked row     if(self.checkedIndexPath)     {         UITableViewCell* uncheckCell = [tableView                      cellForRowAtIndexPath:self.checkedIndexPath];         uncheckCell.accessoryType = UITableViewCellAccessoryNone;     }     UITableViewCell* cell = [tableView cellForRowAtIndexPath:indexPath];     cell.accessoryType = UITableViewCellAccessoryCheckmark;     self.checkedIndexPath = indexPath; } 

If you want to allow the user to be able to uncheck the row by clicking on it again use this code:

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {     // Uncheck the previous checked row     if(self.checkedIndexPath)     {         UITableViewCell* uncheckCell = [tableView                     cellForRowAtIndexPath:self.checkedIndexPath];         uncheckCell.accessoryType = UITableViewCellAccessoryNone;     }     if([self.checkedIndexPath isEqual:indexPath])     {         self.checkedIndexPath = nil;     }     else     {         UITableViewCell* cell = [tableView cellForRowAtIndexPath:indexPath];         cell.accessoryType = UITableViewCellAccessoryCheckmark;         self.checkedIndexPath = indexPath;     } } 
like image 192
idz Avatar answered Oct 11 '22 02:10

idz