Reputation: 121
I have the answers showns in table view i want that if users selet any of the cell is should get checkmarked image with text side and if mean time he selects another cell from first cell checkmark should be removed and shown on the selected
Upvotes: 0
Views: 1190
Reputation: 916
In .h file create variable
UItableviewCell *selectedCell;
In didSelectRow method remove selection from saved cell and save new cell as selected:
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
if (selectedCell) {
selectedCell.accessoryType = UITableViewCellAccessoryNone;
}
UItableviewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
if(cell.accessoryType == UITableViewCellAccessoryCheckmark) {
cell.accessoryType = UITableViewCellAccessoryNone;
else {
cell.accessoryType = UITableViewCellAccessoryCheckmark;
}
selectedCell = cell;
}
To prevent problems with reusable cells u can create NSIndexPath variable instead of UITableViewCell in .h file:
NSIndexPath *selectedCellIndexPath;
and change didSelectRow method:
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
[tableView scrollToRowAtIndexPath:selectedCellIndexPath atScrollPosition:UITableViewScrollPositionMiddle animated:NO];
UITableViewCell *selectedCell = [tableView cellForRowAtIndexPath:selectedCellIndexPath];
selectedCell.accessoryType = UITableViewCellAccessoryNone;
UItableviewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
if(cell.accessoryType == UITableViewCellAccessoryCheckmark) {
cell.accessoryType = UITableViewCellAccessoryNone;
else {
cell.accessoryType = UITableViewCellAccessoryCheckmark;
}
selectedCellIndexPath = indexPath;
}
Upvotes: 1
Reputation: 10828
First add a property to your viewController .h file
@property (nonatomic, strong) NSIndexPath *theSelectedIndexPath;
and in your .m file synthesize
@synthesize theSelectedIndexPath = _theSelectedIndexPath;
Then in your cellForRowAtIndexPath
do
if (indexPath.row == self.theSelectedIndexPath.row) {
cell.accessoryType = UITableViewCellAccessoryCheckmark;
}
else {
cell.accessoryType = UITableViewCellAccessoryNone;
}
Don't forget to update the theSelectedIndexPath
in didSelectRowAtIndexPath
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
self.theSelectedIndexPath = indexPath;
}
Upvotes: 2
Reputation: 2032
selectedRow
tableviewDidSelectRow
set that int to the selected row.tableviewDidSelectRow
make [tableView reloadData];
in your tableView:(UITableView *)tableView cellForRowAtIndexPath
do the following:
if (indexPath.row == selectedRow)
cell.accessoryView = checkMark;
else
cell.accessoryView = nil;
where "checkMark" is an outlet to your checkmark imageview (I use custom checkmarks)
Tada!
Upvotes: 0