Ios UISwitch在滚动TableView时重置

Ios UISwitch在滚动TableView时重置,ios,uitableview,uiswitch,Ios,Uitableview,Uiswitch,我已经找了很长时间了,没有得到任何明确的答案 我的表视图单元格中有一个ui开关作为accessoryView。问题是,每次我滚动表格时,开关都会重置回其原始状态 这是我的cellforrowatinexpath方法: -(UITableViewCell*) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{ static NSString *CellIdentifier =

我已经找了很长时间了,没有得到任何明确的答案

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

这是我的
cellforrowatinexpath
方法:

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

顺便说一句,我已经在头文件中声明了我的开关,并将其设置为属性并合成了它。

因此,您编写的代码将在每次移动到屏幕上时为每个单元格添加一个新按钮。你需要做一些非常类似于你的
iconsImages
iconsList
(我假设这是NSArray的)

以下是您需要做的:

1向头文件添加新的
NSMutableArray
,然后在源文件中正确初始化它。这应该与现有的两个阵列几乎相同。假设您将其称为
iconswitchstates

2创建开关时,设置标签和状态如下:

[switch1 setTag:indexPath.row];
if ([iconsSwitchStates count] > indexPath.row) {
     [switch1 setOn:[iconsSwitchStates objectAtIndex:[indexPath.row]];
}
3在您已有的功能中(
按钮按下:
),您需要设置开关的状态

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

根据Inafziger的回答,我使用了另一种方法(对于一个UISwitch,方法略有不同):

您有一个
NSMutableArray*swState
UISwitch*sw

在您的
cellforrowatinexpath:
方法(您正在创建交换机的地方)中:

在发件人方法中:

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

你的意思是,每次开关从屏幕上滚动*然后再打开时,它会重新打开,或者即使你滚动一点点,它也会改变吗?当开关从屏幕上滚动时,它会改变…这就是我根据代码所想的。这是因为每次它出现在屏幕上,它都是一个新的开关。你有什么建议?…我试着把它放在if(cell==nil)中,但它也不起作用..我不太习惯目标c或iOS…但我尝试了很多不同的东西,但没有运气..我读了一些帖子,他们建议它的cz我重用单元格..请建议!欢迎使用堆栈溢出(SO)!当有人帮助你时,请接受答案,以显示正确的答案,并以他们的帮助增加声誉来奖励他们!
if ([swState count] > 0)
{
     [swState removeObjectAtIndex:0];
}
else
{
     [swState addObject:@"foo"];
}