在UITableView中使用插入行

Bil*_*ill 32 iphone editing insert objective-c uitableview

我希望我的UITableView的行为类似于联系人编辑器中的表格,即用户应该点击编辑,并且每个部分的底部应该出现一个"添加新类别"行.

我使用下面的代码来执行此操作,但问题是没有平滑过渡,因为在联系人中.相反,新行突然出现.我怎样才能获得动画?

另外,我如何回应"添加新类别"行的点击?在我当前的实现中,该行不可单击.

用户开始编辑时是否需要重新加载数据?我这样做是因为否则不会绘制插入行.

谢谢.

- (void)setEditing:(BOOL)editing animated:(BOOL)animated {
    [super setEditing:editing animated:animated];
    [self.tableView setEditing:editing animated:animated];
    [tableView reloadData];
}

- (NSInteger)tableView:(UITableView *)_tableView numberOfRowsInSection:(NSInteger)section {
    // ...
    if( self.tableView.editing ) 
        return 1 + rowCount;
}

- (UITableViewCell *)tableView:(UITableView *)_tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    // .....
    NSArray* items = ...;
    if( indexPath.row >= [items count] ) {
        cell.textLabel.text = @"add new category";
    }
    // ...

    return cell;
}

- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSArray* items = ...;

    if( indexPath.row == [items count] )
        return UITableViewCellEditingStyleInsert;

    return UITableViewCellEditingStyleDelete;
}
Run Code Online (Sandbox Code Playgroud)

Bil*_*ill 36

我错过了一件事.在setEditing:中,我应该做的不是调用reloadData:

- (void)setEditing:(BOOL)editing animated:(BOOL)animated {
    [super setEditing:editing animated:animated];
    [self.tableView setEditing:editing animated:animated]; // not needed if super is a UITableViewController

    NSMutableArray* paths = [[NSMutableArray alloc] init];

    // fill paths of insertion rows here

    if( editing )
        [self.tableView insertRowsAtIndexPaths:paths withRowAnimation:UITableViewRowAnimationBottom];
    else
        [self.tableView deleteRowsAtIndexPaths:paths withRowAnimation:UITableViewRowAnimationBottom];

    [paths release];
}
Run Code Online (Sandbox Code Playgroud)

  • 谢谢Bill,这对我来说非常有用.我在类似的代码中花费了几个小时,但却无法完全正确.这无济于事. (3认同)

luv*_*ere 5

响应行的点击可能在didSelectRowAtIndexPath方法中完成indexPath.row == [items count].对于动画,我建议您看看这里,在insertRowsAtIndexPaths:withRowAnimation:方法.有一个关于如何使用它后在这里.