UISwitch复位时滚动TableView

问题描述:

我一直在寻找这个很长一段时间,并没有得到任何明确的答案。UISwitch复位时滚动TableView

我有一个UISwitch作为accessoryView在我的表格视图单元格中。问题在于,每次滚动表格时,开关都会重置回原来的状态。

这里是我的cellForRowAtIndexPath方法:

-(UITableViewCell*) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{ 

    static NSString *CellIdentifier = @"Cell"; 

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 

    if (cell == nil) { 
     cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease]; 
     cell.selectionStyle = UITableViewCellSelectionStyleNone; 
    } 

    switch1 = [[[UISwitch alloc] initWithFrame:CGRectZero] autorelease]; 
    [switch1 addTarget:self action:@selector(buttonPressed :) forControlEvents:UIControlEventValueChanged]; 
    [switch1 setOn:YES animated:NO]; 
    cell.accessoryView = switch1; 

    NSString *iconsImage = [[self iconsImages] objectAtIndex:[indexPath row]]; 
    UIImage *cellIcon = [UIImage imageNamed:iconsImage]; 
    [[cell imageView] setImage:cellIcon]; 

    CGRect labelFrame = CGRectMake(65, 18, 150, 25); 
    UILabel *iconsNameLabel = [[[UILabel alloc] initWithFrame:labelFrame] autorelease]; 
    iconsNameLabel.font = [UIFont boldSystemFontOfSize:18]; 
    iconsNameLabel.text = [iconsList objectAtIndex:indexPath.row]; 
    [cell.contentView addSubview:iconsNameLabel]; 

    return cell; 
} 

顺便说一句,我宣布我的开关在头文件并将其设置为一个属性,它的合成。

+0

你的意思是说,每次开关在屏幕上滚动**然后重新打开,即使只是滚动一点点,它也会变回来吗? – lnafziger 2012-03-26 23:26:33

+0

当交换机从屏幕上滚动时,它会改变... – GSethi 2012-03-27 01:11:28

+0

这就是我基于代码所想到的。这是因为它每次出现在屏幕上,都是一个新的开关。 – lnafziger 2012-03-27 01:17:41

所以,只要将它移动到屏幕上,写入的代码就会为每个单元添加一个新按钮。你需要做一些非常类似于你的iconsImagesiconsList(我认为它是NSArray的)。

这里就是你需要做的:

1添加一个新的NSMutableArray到你的头文件,然后在适当的源文件进行初始化。这应该与现有的两个阵列几乎相同。假设你称这个iconsSwitchStates

2当您创建的开关,这样设置标签和状态:

[switch1 setTag:indexPath.row]; 
if ([iconsSwitchStates count] > indexPath.row) { 
    [switch1 setOn:[iconsSwitchStates objectAtIndex:[indexPath.row]]; 
} 

3在功能,你已经有(buttonPressed:),你需要设置开关的状态。

[iconsSwitchStates replaceObjectAtIndex:sender.tag withObject:[NSNumber numberWithBool:sender.on]]; 

基于Inafziger的回答,我使用的替代方案(一UISwitch稍有不同的方法):

您的cellforRowAtIndexPath:方法的NSMutableArray *swStateUISwitch *sw

(你在哪里创建开关):

[sw setOn:[swState count]]; 

而在你的发件人方法:

if ([swState count] > 0) 
{ 
    [swState removeObjectAtIndex:0]; 
} 
else 
{ 
    [swState addObject:@"foo"]; 
}