重复使用表格单元格中的 UIswitch

2024-01-15

我的 uiswitch 有问题UITableViewCell每当我更改属于特定部分的特定单元格中的开关值时。所有其他具有相同部分的单元格inexPath.row改变 。请帮忙 ?

这是我的代码cellForRowAtIndexPath method:

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

    //UISwitch *switchview = nil ;

    if (cell == nil)
    {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
                                      reuseIdentifier:CellIdentifier];



    }


    UISwitch *switchController = [[UISwitch alloc] initWithFrame:CGRectZero];
    CGRect switchFrame = switchController.frame;
    NSString *str = [[self.SwitchArray objectAtIndex:indexPath.section] objectAtIndex:indexPath.row];
    NSLog(@"string in cell%@", str);


    //set its x and y value, this you will have to determine how to space it on the left side
    switchFrame.origin.x = 50.0f;
    switchFrame.origin.y = 10.0f;
    switchController.frame = switchFrame;


    [switchController addTarget:self action:@selector(switchChanged:) forControlEvents:UIControlEventValueChanged];
    [cell addSubview:switchController ];
    [addSubview:switchController];


    if ([[[self.SwitchArray objectAtIndex:indexPath.section] objectAtIndex:indexPath.row ]isEqualToString:@"ON"])
 {
        switchController.on=YES;
 }
    else
    {
        switchController.on=NO;
    }


    return cell;

}

这是 SwitchChangedEvent:

-(void)switchChanged:(UISwitch *)sender
{
    UITableViewCell *cell = (UITableViewCell *)[sender superview];
    NSIndexPath *index=[mainTableView indexPathForCell:cell];

    if (sender.on)
    {

        [[self.SwitchArray objectAtIndex:index.section] replaceObjectAtIndex:index.row withObject:@"ON"];
        NSString *word= [[self.mainArray objectAtIndex:index.section ] objectAtIndex:index.row];

    }
    else
    {
        //call the first array by section
        [[self.SwitchArray objectAtIndex:index.section] replaceObjectAtIndex:index.row withObject:@"OFF"];
        NSString *word= [[self.mainArray objectAtIndex:index.section ] objectAtIndex:index.row];


   }

    [padFactoids setObject:[NSKeyedArchiver archivedDataWithRootObject:SwitchArray] forKey:@"savedArray"];
    [padFactoids synchronize];

}

你有两个主要问题:

  1. 这段代码是错误的:

      [cell addSubview:switchController ];
    

    切勿向单元格添加子视图;仅将其添加到单元格中contentView.

  2. 您每次都添加开关cellForRowAtIndexPath:。但这些细胞正在被重复利用。所以一些细胞已经have开关。因此,您要向某些单元添加许多开关。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

重复使用表格单元格中的 UIswitch 的相关文章

随机推荐