2012-01-12 81 views
0

当我从UITableView中选择一行时,该行和其他下面的行(选定的行下面几行)也被选中。预计只有选定的行是选定的行。IPhone:选择不同的行

我的代码是:提前

- (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]; 
} 
} 

谢谢!

回答

0

是的,你要声明一个新的NSMutableArray(比如_selectedList)的数据源数量。用的NSNumber与值0

填充它在h文件(如类成员)

viewDidLoadinit方法声明NSMutableArray *_selectedList;

_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]]; 
} 
+0

它的工作原理!谢谢! – 2012-01-12 11:26:09

2

这可能是因为细胞被重新使用。 如果你想使用的背景颜色来显示选定的状态,你需要设置它在细胞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]; 
    } 

} 
+0

下面的一些选择的一个(我必须滚动看到他们)行不断选择,我向后滚动来选择,这一个可能不被选中,但近一个。这很奇怪。我会尝试另一种方式 – 2012-01-12 10:39:21