-1

我有一个 NSMutableArray 包含序列号 1,2...,n 并有一个 UITableView 显示单元格垂直升序并按顺序显示。我将如何在视觉上和数据中以及在 NSMutableArray 中删除 1 和 n 之间的 m 行,然后将数据中已删除单元格之后的所有单元格的值减 1,并且在视觉上如此firstResponder 不会像 reloadData 方法调用那样放弃控制权?


@interface TableController : UIViewController 

@property (nonatomic, retain) NSMutableArray *data;
@end


@implementation TableController
@synthesize data;

- (id)init
{
  if(self = [super init]) {
    data = [NSArray arrayWithObjects:@"1",@"2",@"3",@"4",@"5",nil];
  }
  return self;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
  return [data count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
  UITableViewCell *cell = [UITableViewCell new];
  [cell.textLabel setText:[data objectAtRow:indexPath.row]];
  return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
  return 20;
}
@end

我将如何删除第 3 行,然后将第 4 行和第 5 行分别变为 3 和 4?

4

2 回答 2

1

只需编辑您的视图模型,然后重新加载表格。

[data removeObjectAtIndex:2];
[tableView reloadData];

另一种选择是UITableView方法deleteRowsAtIndexPaths:withRowAnimation:。这种方法仅适用于 UI,您还必须更新您的视图模型,以防以后重新加载单元格。这种方法的优点是只有您指定的单元格会被更改。现有单元不会重新加载。

如果您要删除的单元格是您的第一响应者,那么您可以通过告诉下一个单元格成为第一响应者来处理这种情况。

于 2014-06-16T16:04:02.783 回答
0

对于用户驱动的删除,您[tableview dataSource]应该实现该方法tableView:commitEditingStyle:forRowAtIndexPath:

这是我的代码中的一个实现……</p>

-(void) tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
  if(editingStyle == UITableViewCellEditingStyleDelete)
  {
    [[STLocationsModel sharedModel] deleteLocationAtIndex: [indexPath row]];
    [tableView deleteRowsAtIndexPaths: @[indexPath] withRowAnimation: UITableViewRowAnimationLeft];
  }
}

要允许编辑,您还需要…</p>

-(BOOL) tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
  return YES;
}

要使表格进入编辑模式以允许删除,您需要将其置于编辑模式。你可以把它放在你的 中viewDidLoad,或者你可以用一个按钮来切换它:

[[self tableView] setEditing:YES animated:NO];

如果您还希望能够在编辑表格时进行选择(同样,这可以在您的viewDidLoad...</p>

[[self tableView] setAllowsSelectionDuringEditing: YES];
于 2014-06-16T16:11:04.930 回答