IOS 表视图(UITableVIew)的使用方法(5)表视图的编辑功能(删除)

时间:2023-03-09 19:31:21
IOS 表视图(UITableVIew)的使用方法(5)表视图的编辑功能(删除)

默认的,如果表视图支持编辑,那用户可以通过两种方式来删除某些行,其一为单击左侧的红色按钮后行右侧显示“Delete”按钮,其二为在单元行上的手指向左滑动,“Delete”按钮也会出现供用户单击。无论哪种方式,只要用户单击了“Delete”,开发者需要确保数据源的更新和处理界面上单元行的消失。

根据这个工作流程开始撰写代码。新建一个继承自上节HBCustomLayoutViewController的子类名为HBDeleteViewController,由于需要一个按钮来触发编辑状态,不如将按钮置于导航栏右侧,设计成点击一次开启编辑模式,再次点击则关闭编辑模式。这样头文件的内容如下:

 #import "HBCustomLayoutViewController.h"

 @interface HBDeleteViewController : HBCustomLayoutViewController

 @property (nonatomic,retain)UIBarButtonItem *editItem;
@property (nonatomic,retain)UIBarButtonItem *doneItem;

在类实现中,数据源已经由HBCustomLayoutViewController制作好,所以只需要对导航栏的按钮进行配置。

 @implementation HBDeleteViewController
@synthesize editItem=_editItem;
@synthesize doneItem=_doneItem; -(void)initUI
{
[super initUI]; //开启编辑模式按钮
_editItem=[[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemEdit target:self action:@selector(actBeginEdit:)]; //关闭编辑模式按钮
_doneItem=[[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(actEndEdit:)]; self.navigationItem.rightBarButtonItem=_editItem;
} #pragma marl-
#pragma mark Action
-(IBAction)actBeginEdit:(id)sender
{
//开启编辑模式
[self.tableView setEditing:YES animated:YES];
self.navigationItem.rightBarButtonItem=_doneItem;
} -(IBAction)actEndEdit:(id)sender
{
//关闭编辑模式
[self.tableView setEditing:NO animated:YES];
self.navigationItem.rightBarButtonItem=_editItem;
}

随后依据删除的工作流程,完成数据源回调函数和代理回调函数的相应实现

#pragma mark
#pragma mark Table View data source
//setEditing:animated:后被调用
//询问具体Cell是不是支持编辑
-(BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
return YES;
} -(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
NSMutableArray *arrNewDatasource=[NSMutableArray arrayWithArray:self.datasource]; //cell上的“delete”按钮点击
if (editingStyle == UITableViewCellEditingStyleDelete) {
if(indexPath.row>=arrNewDatasource.count)
{
return;
} //删除
[arrNewDatasource removeObjectAtIndex:indexPath.row];
//更新datasource
_datasource=[[NSArray alloc]initWithArray:arrNewDatasource]; //更新界面
[self.tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
}
} #pragma mark
#pragma mark TableView Delegate
-(UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
//return UITableViewCellEditingStyleDelete; //只有编辑状态时,才有删除功能
//由于手指左划显示“Delete”按钮并不处于编辑状态,所以会被屏蔽掉
if(self.tableView.editing)
{
return UITableViewCellEditingStyleDelete;
}
return UITableViewCellEditingStyleNone; }

运行代码,其显示效果如下:IOS 表视图(UITableVIew)的使用方法(5)表视图的编辑功能(删除)