表格的修改

表格的修改

一、懒加载 UITableView
- ( UITableView *)tableView
{
   
if ( _tableView == nil ) {
       
_tableView = [[ UITableView alloc ] initWithFrame : self . view . bounds style : UITableViewStylePlain ];
       
       
_tableView . dataSource = self ;
       
_tableView . delegate = self ;
       
        [
self . view addSubview : _tableView ];
    }
   
return _tableView ;
}
注意:
手动实现dataSource和delegate的代理方法

二、在 viewDidLoad方法里面
// 开始编辑,一旦 editing == YES 就默认开启删除模式
  self . tableView . editing = YES ;

// 只要实现了此方法,就能够支持手势拖拽删除了,删除需要自己干!
/**
 UITableViewCellEditingStyleNone,
 UITableViewCellEditingStyleDelete,    
删除
 UITableViewCellEditingStyleInsert     
添加
 */

三、实现代理的其他方法
- (
void )tableView:( UITableView *)tableView commitEditingStyle:( UITableViewCellEditingStyle )editingStyle forRowAtIndexPath:( NSIndexPath *)indexPath
{
   
if (editingStyle == UITableViewCellEditingStyleDelete ) {
       
// 1. 删除 self.dataList indexPath 对应的数据
        [
self . dataList removeObjectAtIndex :indexPath. row ];

       
// 2. 刷新表格 ( 重新加载数据 )
       
// deleteRowsAtIndexPaths 让表格控件动画删除指定的行
        [
self . tableView deleteRowsAtIndexPaths : @[ indexPath ] withRowAnimation : UITableViewRowAnimationMiddle ];
    }
else if (editingStyle == UITableViewCellEditingStyleInsert ) {
       
// 1. 向数组添加数据
        [
self . dataList insertObject : @" 王小二 " atIndex :indexPath.row + 1 ];
       
// 2. 刷新表格
       
// insertRowsAtIndexPaths 让表格控件动画在指定 indexPath 添加指定行
       
// 新建一个 indexPath
       
NSIndexPath *path = [ NSIndexPath indexPathForRow :indexPath. row + 1 inSection :indexPath. section ];
        [
self . tableView insertRowsAtIndexPaths : @[ path ] withRowAnimation : UITableViewRowAnimationMiddle ];
    }
}

// 只要实现此方法,就可以显示拖动控件
- (
void )tableView:( UITableView *)tableView moveRowAtIndexPath:( NSIndexPath *)sourceIndexPath toIndexPath:( NSIndexPath *)destinationIndexPath
{
     // 交换索引,将数据源索引和目标索引交换
//    [self.dataList exchangeObjectAtIndex:sourceIndexPath.row withObjectAtIndex:destinationIndexPath.row];

   
// 1. 将源从数组中取出
   
id source = self . dataList [sourceIndexPath. row ];
   
// 2. 将源从数组中删除
    [
self . dataList removeObjectAtIndex :sourceIndexPath. row ];
   
NSLog ( @"%@" , self . dataList );
   
   
// 3. 将源插入到数组中的目标位置
    [
self . dataList insertObject :source atIndex :destinationIndexPath. row ];
   
   
NSLog ( @"%@" , self . dataList );
}

#pragma mark - 代理方法
// 返回编辑样式,如果没有实现此方法,默认都是删除
- (
UITableViewCellEditingStyle )tableView:( UITableView *)tableView editingStyleForRowAtIndexPath:( NSIndexPath *)indexPath
{

   
return UITableViewCellEditingStyleInsert ;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值