【发布时间】:2013-04-26 14:09:34
【问题描述】:
我在UITableViewCell 中的UISwitch 有问题。当我更改一个开关的值时,向上或向下滚动所有开关都搞砸了。由于可重用性,我使用一个数组来存储每个开关的状态,但每次它们仍然搞砸了。
这里是cellForRowAtIndexPath方法:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell"];
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:@"Cell"];
}
UISwitch *switchController = [[UISwitch alloc] initWithFrame:CGRectZero];
CGRect switchFrame = switchController.frame;
[switchController setOn:YES animated:NO];
//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 ];
UILabel *label ;
label=(UILabel *)[cell viewWithTag:1];
NSString *value = [[mainArray objectAtIndex:indexPath.section] objectAtIndex:indexPath.row];
label.text = value;
label.textAlignment = NSTextAlignmentRight;
label.autoresizingMask = UIViewAutoresizingFlexibleRightMargin;
//This for persist switch state when scroll up or down
if ([[[self.SwitchArray objectAtIndex:indexPath.section] objectAtIndex:indexPath.row ]isEqualToString:@"ON"])
{
switchController.on=YES;
}
else
{
switchController.on=NO;
}
return cell;
}
这里是 SwitchChanged 事件:
-(void)switchChanged:(UISwitch *)sender
{
UITableViewCell *cell = (UITableViewCell *)[[sender superview] 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];
}
非常感谢您的帮助。
【问题讨论】:
-
尝试设置断点并查看
self.SwitchArray以确保它存在(不是nil)并包含您期望的数据。我猜你的数组是nil,所以你的返回开关一直处于关闭状态。 -
@DBD 比你的回应。但我的意思并不是所有的开关都关闭了。我的意思是,每当我更改表格视图上的一个开关然后向上或向下滚动时,它们就会变得一团糟,关闭的开关打开,反之亦然。
-
正如 ChrisH 所提到的,每次配置单元时,您都会创建一个新的
UISwitch,即使开关已经存在。这是您必须解决的问题,但我仍然认为您需要检查数据模型,因为我不相信您的价值观会像您认为的那样保存在其中。
标签: ios objective-c uitableview uiswitch