【问题标题】:UISwitch Resets when scrolling TableView滚动 TableView 时 UISwitch 重置
【发布时间】:2012-03-26 23:10:35
【问题描述】:

这个问题我找了很久,没有一个明确的答案。

我的表格视图单元格中有一个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; 
}

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

【问题讨论】:

  • 你的意思是每次开关滚动*离开屏幕然后重新打开,它又重新打开,还是即使你滚动一点它也会改变?
  • 当开关滚出屏幕时它会改变...
  • 这就是我根据代码想到的。因为每次出现在屏幕上都是一个新的开关。
  • 你有什么建议?...我试过把它放在 if(cell == nil) 但它也不起作用..我不太习惯目标 c 或 iOS...但是我尝试了很多不同的东西,但没有运气..我读了一些帖子,他们建议它的 cz 我重用细胞..请建议!
  • 欢迎来到 Stack Overflow (SO)!当有人帮助您时,请接受答案,以便显示正确答案并奖励他们的帮助以增加声誉!

标签: ios uitableview uiswitch


【解决方案1】:

因此,您编写的代码将在每个单元格移动到屏幕上时为其添加一个新按钮。你需要做一些与你的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]];

【讨论】:

    【解决方案2】:

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

    您有一个NSMutableArray *swStateUISwitch *sw

    在您的 cellforRowAtIndexPath: 方法中(您在其中创建开关):

    [sw setOn:[swState count]];
    

    在你的发件人方法中:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多