我正在尝试实现可选择的 ListView 。 ListView 包含一些名称。您可以选择或取消选择多个名称。如果选择了名称,单元格样式将更改为 UITableViewCellAccessoryCheckmark
。
但是现在我遇到了一个问题。在取消选择名称之前,您必须多次按单元格。这是因为 didSelectRowAtIndexPath
总是先被调用。
// cellForRowAtIndexPath function
if ([assignedPlayers containsObject:player.persistentData])
{
[cell setSelected:true];
[cell setAccessoryType: UITableViewCellAccessoryCheckmark];
}
cell.textLabel.text = [NSString stringWithFormat:@"%@", player.persistentData.name];
return cell;
}
- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath
{
[[tableView cellForRowAtIndexPath:indexPath] setSelected:FALSE];
[[tableView cellForRowAtIndexPath:indexPath] setAccessoryType: UITableViewCellAccessoryNone];
[self.eventController removePlayerFromEvent:_editingEvent :[self.playerController getPlayerAtPosition:indexPath.row]];
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
[[tableView cellForRowAtIndexPath:indexPath] setSelected:TRUE];
[[tableView cellForRowAtIndexPath:indexPath] setAccessoryType: UITableViewCellAccessoryCheckmark];
[self.eventController addPlayerToEvent:_editingEvent :[self.playerController getPlayerAtPosition:indexPath.row]];
}
现在我不知道如何解决这个问题。
感谢您的帮助。
最佳答案
看看下面的示例,其中 _selectedList
包含选定的玩家,_datasoureArray
是包含所有玩家姓名的数据源。
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CELL"];
if(cell == nil)
{
cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"CELL"];
}
cell.textLabel.text = [_datasoureArray objectAtIndex:indexPath.row];
if([_selectedList containsObject:[_datasoureArray objectAtIndex:indexPath.row]]) //hear selected list is an mutable array wich holds only selected player
{
cell.selected = YES;
cell.accessoryType = UITableViewCellAccessoryCheckmark;
}
else
{
cell.selected = NO;
cell.accessoryType = UITableViewCellAccessoryNone;
}
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
if(cell)
{
if(cell.accessoryType == UITableViewCellAccessoryNone)
{
[_selectedList addObject:[_datasoureArray objectAtIndex:indexPath.row]];//add
}
else
{
if([_selectedList containsObject:[_datasoureArray objectAtIndex:indexPath.row]])
{
[_selectedList removeObject:[_datasoureArray objectAtIndex:indexPath.row]]; //remove
}
}
}
[tableView reloadData];
NSLog(@"%@",_selectedList.description);
}
关于ios - UITableView可选择列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24926005/