UITableViewCell设置编辑功能

#import "ViewController.h"


@interface ViewController ()<UITableViewDataSource,UITableViewDelegate>

@property (weak, nonatomic) IBOutlet UITableView *tableView;


@property  BOOL flag;


@end


@implementation ViewController

- (IBAction)add:(id)sender

{

    self.flag = YES;

    self.tableView.editing = !self.tableView.editing;

}


- (IBAction)delete:(id)sender

{

    self.flag = NO;

    self.tableView.editing = !self.tableView.editing;

}



- (void)viewDidLoad

{

    [super viewDidLoad];

    

    self.tableView.dataSource = self;

    

    self.tableView.delegate = self;

    

    self.datas = [[NSMutableArray alloc]init];

    

    for (int i = 1; i <=30; i ++)

    {

        NSString *str = [NSString stringWithFormat:@"产品%0.2d",i];

    

    [self.datas addObject:str];

    }

    

}


-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section

{

    return self.datas.count;

    

}


-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath


{

    static NSString *cellID = @"mycell";

    UITableViewCell *cell =[self.tableView dequeueReusableCellWithIdentifier:cellID];

    if (cell ==nil)

    {

        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellID];

        

        

    }

    cell.textLabel.text = self.datas[indexPath.row];

    return cell;

}


#pragma mark - tableView的代理方法

#pragma mark 执行相应的编辑

-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath

{

    if (editingStyle ==UITableViewCellEditingStyleDelete)

    {

        

    //1、先删除数据

    [self.datas removeObjectAtIndex:indexPath.row];

    //2、局部刷新表格

    [self.tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationLeft];

    }

    else

    {

        //在当前行插入数据

        NSString *str = [NSString stringWithFormat:@"新产品%02d",arc4random()%10];

        

        [self.datas insertObject:str atIndex:indexPath.row];

        //局部刷新表格

        [self.tableView insertRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationLeft];

    }

}

#pragma mark 设置可编辑单元格的内容

-(UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath

{

    if (self.flag)

    {

        return UITableViewCellEditingStyleInsert;

    }

    else

    {

        return UITableViewCellEditingStyleDelete;

    }

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值