抱歉,我对 iOS 开发还很陌生。
我有一个UITableView
从单个 XiB 笔尖拉出的单元进行设置。我在笔尖中创建了一个开/关开关,并且我试图保存开关的状态viewWillDisappear
我拥有的细胞数量。 (准确地说是 6 个单元)。
如何循环遍历所有单元格并保存此信息?
我在 UIViewController 中尝试了此操作来获取一个单元格的信息:
- (void)viewDidDisappear:(BOOL)animated
{
[super viewDidDisappear:animated];
UITableView *tv = (UITableView *)self.view;
UITableViewCell *tvc = [tv cellForRowAtIndexPath:0];
}
它给我错误“程序收到信号:”EXC_BAD_INSTRUCTION”。
我怎样才能做到这一点?
您必须通过有效的NSIndexPath
to cellForRowAtIndexPath:
。你使用了0,这意味着没有indexPath。
你应该使用这样的东西:
UITableViewCell *tvc = [tv cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]];
BUT。不要这样做。不要在 UITableViewCell 中保存状态。
当开关更改其状态时更新您的数据源。
如果您已经实现了 UITableViewDataSource 方法,那么您的 tableView 重用单元格的原因就正确了。这意味着当细胞被重复使用时,细胞的状态将消失。
您的方法可能适用于 6 个单元。但 9 个电池就会失败。
如果您将第一个单元格滚动到屏幕之外,它甚至可能会失败。
我写了一个快速演示(如果你不使用 ARC addrelease
在必要的地方)向您展示应该如何做:
- (void)viewDidLoad
{
[super viewDidLoad];
self.dataSource = [NSMutableArray arrayWithCapacity:6];
for (NSInteger i = 0; i < 6; i++) {
[self.dataSource addObject:[NSNumber numberWithBool:YES]];
}
}
- (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];
UISwitch *aSwitch = [[UISwitch alloc] init];
[aSwitch addTarget:self action:@selector(switchChanged:) forControlEvents:UIControlEventValueChanged];
cell.accessoryView = aSwitch;
}
UISwitch *aSwitch = (UISwitch *)cell.accessoryView;
aSwitch.on = [[self.dataSource objectAtIndex:indexPath.row] boolValue];
/* configure cell */
return cell;
}
- (IBAction)switchChanged:(UISwitch *)sender
{
// UITableViewCell *cell = (UITableViewCell *)[sender superview];
// NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
CGPoint senderOriginInTableView = [sender convertPoint:CGPointZero toView:self.tableView];
NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:senderOriginInTableView];
[self.dataSource replaceObjectAtIndex:indexPath.row withObject:[NSNumber numberWithBool:sender.on]];
}
如您所见,不在单元格中存储状态并不是很复杂:-)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)