IPhone:选择了不同的行
当我从UITableView中选择一行时,该行和下面的其他行(所选行下面的几行)也会被选中。仅所选行应为所选行 我的代码是:IPhone:选择了不同的行,iphone,rows,multipleselection,Iphone,Rows,Multipleselection,当我从UITableView中选择一行时,该行和下面的其他行(所选行下面的几行)也会被选中。仅所选行应为所选行 我的代码是: - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath]; if (cell.accessoryType =
- (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];
}
}
提前谢谢 这可能是因为细胞被重复使用了。 如果要使用背景色来显示选定的状态,则需要在cell geter方法中进行设置 添加此代码应该可以:
- (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];
}
}
是的,您必须声明数据源计数的新
NSMutableArray
(比如\u selectedList
)。使用值为0的NSNumber填充它
声明NSMutableArray*\u selectedList代码>在.h文件中(作为类成员)
在viewDidLoad
或init
方法中
_selectedList = [[NSMutableArray alloc] init];
for( int i = 0; i < [datasource count]; i++ )
{
[_selectedList addObject:[NSNumber numberWithBool:NO]];
}
选定行下面的一些行(我必须滚动才能看到它们)保持选中状态,并且,我滚动回选定行,这一行可能未被选中,但近一行已被选中。这很奇怪。我会试着用另一种方式做
- (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]];
}