在UITableView中动态的插入或删除行

在UITableView中插入或者删除指定的行(或者节)使用的是如下几个API:

insertRowsAtIndexPath: withRowAnimation: 在指定位置插入行

deleteRowsAtIndexPath: withRowAnimation: 删除指定行

insertSections: withRowAnimation: 在指定位置插入节

deleteSections: withRowAnimation: 删除指定节

调用以上API之前,必须先调用beginUpdates,插入/删除数据完成后再调用endUpdates。

-(IBAction)addRows:(id)sender{

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

for (int i=0; i<3; i++) {

NSString *s = [[NSString alloc] initWithFormat:@”hello %d”,i];

[datas addObject:s];

NSIndexPath *indexPath = [NSIndexPath indexPathForRow:i inSection:0];

[indexPaths addObject: indexPath];

}

[self.tableView beginUpdates];

[self.tableView insertRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewScrollPositionNone];

[self.tableView endUpdates];

}

-(IBAction)delRows:(id)sender{

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

[datas removeObjectAtIndex:0];

[indexPaths addObject:[NSIndexPath indexPathForRow:0 inSection:0]];

[self.tableView beginUpdates];

[self.tableView deleteRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewRowAnimationNone];

[self.tableView endUpdates];

}

需要注意的是,调用insert函数时,需保证数据源添加的记录数要与你想插入的行的总数一致,如上面的例子中,想要插入的记录有3条,插入位置分别为1,2,3,则对应的indexpPaths数组的元素总数为3,数组元素为一个NSIndexPath对象,通过它我们指定了记录的插入位置。删除数据也是相同的道理。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值