gpt4 book ai didi

ios - 重用表格单元格中的 UIswitch

转载 作者:行者123 更新时间:2023-11-28 20:20:32 25 4
gpt4 key购买 nike

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

这是我的cellForRowAtIndexPath 方法代码:

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

    永远不要向单元格添加 subview ;仅将其添加到单元格的 contentView

  2. 您每次都通过 cellForRowAtIndexPath: 添加开关。但是这些电池正在被重复使用。所以一些细胞已经了开关。因此,您正在向某些单元格添加许多开关。

关于ios - 重用表格单元格中的 UIswitch,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16223386/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com