1

任何人都可以解释如何正确实现该tableView:commitEditingStyle:forRowAtIndexPath:方法,以便我可以从支持数组中正确删除一个项目并仅显示我尚未删除的项目?

这是我到目前为止所拥有的:

@interface ViewController : UIViewController <UITableViewDelegate,UITableViewDataSource>
{
    IBOutlet UITableView *tableView;

    NSArray *allItems;
    NSMutableArray *displayItems;
}

@end

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    allItems = [[NSArray alloc] initWithObjects:@"One",@"Two",@"Three",@"Four",@"Five",@"Six",@"Seven", nil];
    displayItems = [[NSMutableArray alloc] initWithArray:allItems];
}

-(UITableViewCell*) tableView:(UITableView *)aTableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
    }
    cell.textLabel.text = [displayItems objectAtIndex:indexPath.row];
    return cell;
}

@end
4

2 回答 2

3

实现您tableView:commitEditingStyle:forRowAtIndexPath:的如下:

// Override to support editing the table view.
- (void)tableView:(UITableView *)aTableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {

    if (editingStyle == UITableViewCellEditingStyleDelete) {

        // remove the object from display array
        [displayItems removeObjectAtIndex:indexPath.row];

        // Delete the row from the data source.
        [aTableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];

    }   
    else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view.
    }   
}
于 2012-03-19T12:52:22.530 回答
3

尝试这个:

// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {

    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source.
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
        if(!deletedIndices) deletedIndices = [[NSMutableIndexSet alloc] initWithIndex:indexPath.row];
        else [deletedIndices addIndex:indexPath.row];
    }   
    else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view.
    }   
}

-(IBAction)editingDidComplete:(id)sender
{

    // remove the objects from display array
    [valueArray removeObjectsAtIndexes:deletedIndices];
    // Reload tableView if needed
    [mainTableView reloadData];
    [mainTableView setEditing:NO];
 }
于 2012-03-19T12:44:23.960 回答