我有一个表格视图。我可以添加和删除单元格。免得说我添加5.当我离开表视图(切换视图),并返回到表视图时,单元格消失了。为什么会这样?另外,我怎么能解决这个问题?谢谢!
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath: (NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Cell";
cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
stepper = [[UIStepper alloc]init];
[stepper setFrame:CGRectMake(216, 22, 100, 30)];
NSLog(@"the stepper is %@", stepper);
[cell addSubview:stepper];
cellLabel = [[UILabel alloc]init];
[cellLabel setFrame:CGRectMake(65, 22, 27, 27)];
[cellLabel setText:@"1"];
[cell.contentView addSubview:cellLabel];
}
[cell setSelectionStyle:UITableViewCellSelectionStyleNone];
cell.imageView.image = [imageArray objectAtIndex:indexPath.row];
// cell.textLabel.text = [cells objectAtIndex:indexPath.row];
if ([cell.imageView.image isEqual:[UIImage imageNamed:@"paddle5.png"]]) {
[cellLabel setFrame:CGRectMake (175, 22, 30, 30)];
}
if ([cell.imageView.image isEqual:[UIImage imageNamed:@"paddle4.png"]]) {
[cellLabel setFrame:CGRectMake (150, 22, 30, 30)];
}
if ([cell.imageView.image isEqual:[UIImage imageNamed:@"paddle3.png"]]) {
[cellLabel setFrame:CGRectMake (120, 22, 30, 30)];
}
if ([cell.imageView.image isEqual:[UIImage imageNamed:@"paddle2.png"]]) {
[cellLabel setFrame:CGRectMake (90, 22, 30, 30)];
}
return cell;
}
NumberOfRows
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [cells count];
}
CommitEditingStyle:
- (void) tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle
forRowAtIndexPath:(NSIndexPath *)indexPath
{
if (editingStyle == UITableViewCellEditingStyleDelete)
{
[[self cells] removeObjectAtIndex:[indexPath row]];
[[self imageArray]removeObjectAtIndex:[indexPath row]];
NSArray *indexPaths = [NSArray arrayWithObject:indexPath];
[[self myTableView] deleteRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewRowAnimationFade];
}
}
答案 0 :(得分:3)
看起来tableView:commitEditingStyle:forRowAtIndexPath:
的代码缺少插入操作的部分:
else if (editingStyle == UITableViewCellEditingStyleInsert) {
[[self imageArray] insertObject:... atIndex:...];
}
如果没有此代码,当您切换并返回时,imageArray
只有旧对象。
您还应该在方法结束时从模型重新加载数据:
[tableView reloadData];