天天看點

iOS項目開發小技巧 (三) --UITableView實作Cell左劃删除等自定義功能

今天來介紹下iOS開發中UITableView的Cell左劃實作微信中置頂,删除等功能。該功能在iOS8.0以前是需要很複雜的實作,不過github上應該有現成demo,不過今天介紹的是在iOS8.0以後蘋果新推出的api,來實作Cell左劃自定義控件。

1. 首先建立UITableView視圖,實作其倆個代理,UITableViewDelegate和UITableViewDataSource,該處代碼就不說了,主要是倆個回調方法

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

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

2. 然後實作另一個代理方法

-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath { editingStyle = UITableViewCellEditingStyleDelete;//此處的EditingStyle可等于任意UITableViewCellEditingStyle,該行代碼隻在iOS8.0以前版本有作用,也可以不實作。 }

3. 再實作

`-(NSArray )tableView:(UITableView )tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath

{

UITableViewRowAction *deleteRoWAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDestructive title:@”删除” handler:^(UITableViewRowAction *action, NSIndexPath *indexPath) {//title可自已定義

NSLog(@”點選删除”);

}];//此處是iOS8.0以後蘋果最新推出的api,UITableViewRowAction,Style是劃出的标簽顔色等狀态的定義,這裡也可自行定義

UITableViewRowAction *editRowAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleNormal title:@"編輯" handler:^(UITableViewRowAction *action, NSIndexPath *indexPath) {

}];
editRowAction.backgroundColor = [UIColor colorWithRed:0 green:124/255.0 blue:223/255.0 alpha:1];//可以定義RowAction的顔色
 return @[deleteRoWAction, editRowAction];//最後傳回這倆個RowAction 的數組
           

}`

這樣就實作了如下的效果

iOS項目開發小技巧 (三) --UITableView實作Cell左劃删除等自定義功能

另附:

iOS8.0以前實作UITableViewCell左劃多個标簽的Demo參考