4.12 Deleting Cells and Sections from Table Views

来源:互联网 发布:用sql创建表 编辑:程序博客网 时间:2024/05/16 04:19

删除Cells或Sections

删除Sectionde 步骤
1:删除data source中对应的数据
2:调用UITableView 实例方法deleteSections:withRowAnimation:
第一个参数是NSIndexSet 类型,可以用类方法创建indexSetWithIndex:,不过这个只能删除一个Section,想一次删除更多,用这个indexSetWithIndexesInRange:

删除cell步骤
1:删除data source中对应的数据
2:调用UITableView 实例方法deleteRowsAtIndexPaths:withRowAnimation:第一个参数是NSArray类型,里面包含了NSIndexPath类型的数据。NSIndexPath有类方法来创建对象indexPathForRow:inSection:

下面上下小例子
 NSMutableArray *tableSections=nil;//数据源
 //初始化数据源数据
 tableSections = [NSMutableArray array];
    for (int iSection = 0; iSection < 3; iSection++) {
       
        NSMutableArray *rows = [NSMutableArray array];
        for (int i=0; i<3; i++) {
            [rows addObject:[NSString stringWithFormat:@"Section %d Row %d",iSection, i]];
        }
        [tableSections addObject:rows];
    }
   
 //导航栏放3个按钮
    [self addNavigationBar];//实现自己写
    UIBarButtonItem * rightButton = [[UIBarButtonItem alloc] initWithTitle:@"删除Section" style:UIBarButtonItemStyleBordered target:self action:@selector(deletedSection:)];
    UIBarButtonItem * rightButton1 = [[UIBarButtonItem alloc] initWithTitle:@"删除Cell" style:UIBarButtonItemStyleBordered target:self action:@selector(deletedCell:)];
    UIBarButtonItem * rightButton2 = [[UIBarButtonItem alloc] initWithTitle:@"删除Cells" style:UIBarButtonItemStyleBordered target:self action:@selector(deletedCells:)];
    NSArray *rightBtns = [NSArray arrayWithObjects:rightButton,rightButton1,rightButton2, nil];
    self.navigationItem.rightBarButtonItems = rightBtns;

 //删除section
-(void)deletedSection:(id)sender
{
    id obj = [tableSections firstObject];
    if (obj != nil) {
        [tableSections removeObject:obj];
        [_tableView deleteSections:[NSIndexSet indexSetWithIndex:0] withRowAnimation:UITableViewRowAnimationAutomatic];
//        [tableSections removeObjectAtIndex:0];
//        [_tableView deleteSections:[NSIndexSet indexSetWithIndexesInRange:NSMakeRange(0, 2)] withRowAnimation:UITableViewRowAnimationAutomatic];//删除多个
    }
}

//删除一行
-(void)deletedCell:(id)sender
{
    if (markIndexPath != nil) {
        [[tableSections objectAtIndex:markIndexPath.section] removeObjectAtIndex:markIndexPath.row];
        [_tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:markIndexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
        markIndexPath = nil;
    }
   
}


//删除多行
-(void)deletedCells:(id)sender
{
    NSMutableArray * array = [NSMutableArray array];
    for (int i=0; i < 3; i++) {
        [[tableSections objectAtIndex:i] removeObjectAtIndex:0];
        [array addObject:[NSIndexPath indexPathForItem:0 inSection:i]];
    }
    [_tableView deleteRowsAtIndexPaths:array withRowAnimation:UITableViewRowAnimationAutomatic];
   
}