IPhone: different row selected
-
27-10-2019 - |
Question
When I select a row from a UITableView, that row and others below (several rows below the one selected) are also selected. Only the selected row is expected to be the selected one.
My code is:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
if (cell.accessoryType == UITableViewCellAccessoryCheckmark) {
//Deselect
cell.accessoryType = UITableViewCellAccessoryNone;
cell.backgroundColor=[UIColor clearColor];
} else {
//Select
cell.accessoryType = UITableViewCellAccessoryCheckmark;
cell.backgroundColor=[UIColor redColor];
}
}
Thanks in advance!
Solution
Yes, you have to declare a new NSMutableArray
(say _selectedList
) of your datasource count. Populate it with NSNumber with value 0.
Declare NSMutableArray *_selectedList;
in .h file (as class member)
In viewDidLoad
or init
method,
_selectedList = [[NSMutableArray alloc] init];
for( int i = 0; i < [datasource count]; i++ )
{
[_selectedList addObject:[NSNumber numberWithBool:NO]];
}
And make the following methods as follows.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
//...
if (! [[_selectedList objectAtIndex:indexPath.row] boolValue]) {
//Deselected
cell.accessoryType = UITableViewCellAccessoryNone;
cell.backgroundColor=[UIColor clearColor];
} else {
//Selected
cell.accessoryType = UITableViewCellAccessoryCheckmark;
cell.backgroundColor=[UIColor redColor];
}
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
if (cell.accessoryType == UITableViewCellAccessoryCheckmark) {
//Deselect
cell.accessoryType = UITableViewCellAccessoryNone;
cell.backgroundColor=[UIColor clearColor];
} else {
//Select
cell.accessoryType = UITableViewCellAccessoryCheckmark;
cell.backgroundColor=[UIColor redColor];
}
BOOL isSelected = ![[_selectedList objectAtIndex:indexPath.row] boolValue];
[_selectedList replaceObjectAtIndex:indexPath.row withObject:[NSNumber numberWithBool:isSelected]];
}
OTHER TIPS
That's probably because the cells are re-used. If you want to use the background color to show the selected state, you need to set it in the cell geter method
Adding this code should work :
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
//...
if (!cell.selected) {
//Deselected
cell.accessoryType = UITableViewCellAccessoryNone;
cell.backgroundColor=[UIColor clearColor];
} else {
//Selected
cell.accessoryType = UITableViewCellAccessoryCheckmark;
cell.backgroundColor=[UIColor redColor];
}
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow