#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;
}
}