-
新建一個包含UITableView的View并綁定好測試數(shù)據(jù)哎垦,本文所用的布局如下圖
-
分別對添加、編輯恃疯、修改漏设、刪除四個按鈕添加點擊事件
-
添加按鈕的實現(xiàn)代碼
- (IBAction)Add:(UIButton *)sender { WXData *data = [[WXData alloc]init]; data.price =[NSString stringWithFormat:@"%d",arc4random_uniform(1000)]; data.title = @"我是新增的"; data.buyCount = @"22"; data.icon = @"2c97690e72365e38e3e2a95b934b8dd2"; // 在數(shù)據(jù)源的第一個位置插入數(shù)據(jù) [self.list insertObject:data atIndex:0]; // 刷新插入行,有動畫效果 [self.tableView insertRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:0 inSection:0]] withRowAnimation:UITableViewRowAnimationLeft]; // 刷新全部數(shù)據(jù)澡谭,但是沒有動畫效果 // self.tableView reloadData];
-
}
```
-
編輯按鈕的實現(xiàn)代碼
- (IBAction)Edit:(UIButton *)sender { // 設(shè)置tableView是否進入編輯模式 [self.tableView setEditing:!self.tableView.isEditing animated:YES];
}
```
-
刪除按鈕的實現(xiàn)代碼
- (IBAction)remove:(UIButton *)sender { [self.list removeObjectAtIndex:0]; //從模型中刪除 [self.tableView deleteRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:0 inSection:0]] withRowAnimation:UITableViewRowAnimationRight]; }
-
更新按鈕的實現(xiàn)代碼
- (IBAction)Update:(UIButton *)sender { WXData *data = self.list[0]; data.price = [NSString stringWithFormat:@"%d",50 + arc4random_uniform(100)]; [self.tableView reloadData];
}
```
-
效果如下
-
注意點
- tableView的數(shù)據(jù)操作全部是通過模型數(shù)據(jù)來進行的愿题,應(yīng)該先修改模型數(shù)據(jù)再調(diào)用刷新方法。
-
不要直接修改Cell上面控件蛙奖,比如直接修改某個label的text屬性潘酗。不要直接修改Cell上面控件,比如直接修改某個label的text屬性雁仲。不要直接修改Cell上面控件仔夺,比如直接修改某個label的text屬性。
-
左滑刪除效果
- UITableView的左滑刪除方法只需要實現(xiàn)-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath 方法攒砖,功能實現(xiàn)需要寫到該方法中缸兔。
-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{ if(editingStyle == UITableViewCellEditingStyleDelete){ // 刪除 [self.list removeObjectAtIndex:indexPath.row]; //從模型中刪除 [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationLeft]; } if(editingStyle == UITableViewCellEditingStyleInsert) // 新增 { NSLog(@"新增"); }
}
![](http://upload-images.jianshu.io/upload_images/1717369-b2edd828bf6b9bc5.jpg?imageMogr2/auto-orient/strip)
- ###小tips
可能以后會碰到奇葩需求,需要在編輯狀態(tài)下需要有新增按鈕吹艇,apple其實是有提供的惰蜜。只需要實現(xiàn)- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath方法即可。
```objc
/**
* 這個方法決定了編輯模式時受神,每一行的編輯類型:insert(+按鈕)抛猖、delete(-按鈕)
*/
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
return indexPath.row % 2 == 0? UITableViewCellEditingStyleInsert : UITableViewCellEditingStyleDelete;
}
```
![](http://upload-images.jianshu.io/upload_images/1717369-f7ea018cc987a053.jpg?imageMogr2/auto-orient/strip)