2014-04-29 39 views
0

我的UITableViewCell原型中有一个UISwitch。UITableView中的UISwitch Bug

问题是,当我打开其中一个开关时,其中一个未显示的开关也打开。

这不会发生在显示所有单元格的iPad版本中。

下面是一些代码:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { 
    static NSString *identifier = @"Cell"; 
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier]; 

    Notification *notification = [notifications objectAtIndex:indexPath.row]; 

    UILabel *titleLabel = (UILabel *) [cell viewWithTag:100]; 
    UISwitch *newsSwitch = (UISwitch *) [cell viewWithTag:101]; 
    UIImageView *imageView = (UIImageView *) [cell viewWithTag:102]; 

    [titleLabel setText:[notification name]]; 
    [imageView setImage:[UIImage imageNamed:[notification image]]]; 

    BOOL isOn = [storage boolForKey:[NSString stringWithFormat:@"notification_%@", [notification name]]]; 
    [newsSwitch setOn:isOn]; 
    [newsSwitch setTag:indexPath.row]; 
    [newsSwitch addTarget:self action:@selector(didChangeStateForSwitch:) forControlEvents:UIControlEventValueChanged]; 

    return cell; 
} 
+0

你的意思是,还没有在屏幕上的开关也打开?然后这个错误很可能出现在你的'didChangeStateForSwitch:'方法中,请更新你的问题并告诉我们这个方法的代码。 – DarkDust

+0

我从didChangeStateForSwitch中删除了代码:并且行为相同。 –

回答

1

你的问题是,你首先通过它的标签查询开关:

UISwitch *newsSwitch = (UISwitch *) [cell viewWithTag:101]; 

但后来对,您更改标签:

[newsSwitch setTag:indexPath.row]; 

所以当单元格将得到[R eused,交换机将不会被发现,因为现在它的标签不再是101了。因此,交换机将停留在旧状态。

您可以通过在查询交换机后添加NSLog(@"Switch: %@", newsSwitch);来轻松进行验证。你会发现它将输出Switch: (null)那些你有错误的开关值的行。

解决方法是不修改标签。

问题是,你如何记住开关的哪一行?一种方法是:

- (void)didChangeStateForSwitch:(id)sender 
{ 
    NSIndexPath *indexPath = [myTableView indexPathForCell:[sender superview]]; 
    ... 
} 

另一种可能性是使用associated objects

+0

你的回答是正确的,那就是问题所在。但解决方案并不适合我。我以编程方式创建了UISwitch。它现在工作正常。谢谢。 –

1

第一次当你加载你正在与标签101的视图switch.Few系的细胞后,你是新的标签设置这个开关,下一次当您尝试使用标记101来查看它不存在的视图。 [newsSwitch setTag:indexPath.row];删除这条线,然后再试一次

你可以得到该指数路径@DarkDust建议

- (void)didChangeStateForSwitch:(id)sender 
{ 
NSIndexPath *indexPath = [myTableView indexPathForCell:[sender superview]]; 
... 
} 
+0

“[storage boolForKey:[NSString stringWithFormat:@”notification _%@“,[notification name]]];”是不足够的? –

+0

之前发生过我。就像@wootage说你应该保持你的开关状态在一个数组中,并将其设置在你的cellForRowAtIndexPath中 – Pancho

+0

你必须实现CustomTableViewCell,并给每个开关uniq标签,以解决它在didChangeStateForSwitch! –