4.12 Deleting Cells and Sections from Table Views

删除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];
   
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值