- (void)loadView
{
// 1. 视图
self.view = [[UIView alloc]initWithFrame:[[UIScreen mainScreen]applicationFrame]];
// 2. 工具栏
UIToolbar *toolbar = [[UIToolbar alloc]initWithFrame:CGRectMake(0, 0, 320, 44)];
[toolbar setTintColor:[UIColor redColor]];
// 1)间距按钮
UIBarButtonItem *space = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
// 2) 添加按钮
UIBarButtonItem *item1 = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(add)];
[item1 setStyle:UIBarButtonItemStyleBordered];
// 注意!!!
[toolbar setItems:@[space, item1]];
[self.view addSubview:toolbar];
// 3) 添加标签
UILabel *label = [[UILabel alloc]initWithFrame:toolbar.bounds];
[label setBackgroundColor:[UIColor clearColor]];
[label setText:@"商品列表"];
[label setTextAlignment:NSTextAlignmentCenter];
[label setFont:[UIFont systemFontOfSize:20]];
[toolbar addSubview:label];
// 3. 表格
UITableView *tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 44, 320, 416) style:UITableViewStylePlain];
[tableView setDataSource:self];
[tableView setDelegate:self];
[self.view addSubview:tableView];
self.tableView = tableView;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// 初始化数据
NSMutableArray *array = [NSMutableArray arrayWithCapacity:50];
for (NSInteger i = 0; i < 50; i++) {
NSString *str = [NSString stringWithFormat:@"商品-%03d", i];
[array addObject:str];
}
self.dataList = array;
}
#pragma mark - 数据源方法
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return self.dataList.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil];
NSString *str = self.dataList[indexPath.row];
[cell.textLabel setText:str];
return cell;
}
#pragma mark - 代理方法
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
NSLog(@"编辑样式 %d", editingStyle);
if (UITableViewCellEditingStyleInsert == editingStyle) {
// 1. 像数组增加数据
NSString *str = @"new Product";
// 在当前选中操作行的后面增加一条记录
[self.dataList insertObject:str atIndex:indexPath.row + 1];
// 2. 刷新数据
// 参数array是“新增”数据行对应的indexPath的数组
NSIndexPath *newPath = [NSIndexPath indexPathForRow:indexPath.row + 1 inSection:indexPath.section];
[self.tableView insertRowsAtIndexPaths:@[newPath] withRowAnimation:UITableViewRowAnimationRight];
NSLog(@"%@", self.dataList);
}
}
// 通知表格应该变成什么编辑样式,如果不写此方法,默认都是删除
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
return self.tableView.tag;
}
#pragma mark 按钮监听方法
- (void)add
{
[self.tableView setTag:UITableViewCellEditingStyleInsert];
BOOL isEditing = self.tableView.isEditing;
[self.tableView setEditing:!isEditing animated:YES];
}
@end