UITableView多选Cell操作

来源:互联网 发布:java bytebuffer 读取 编辑:程序博客网 时间:2024/04/29 05:34

先新建一个项目,命名为UITableViewDemo,storyboard中拖入一个UITableViewController,然后新建一个继承自UITableViewController的类,命名为UDTableViewController。在storyboard中将拖入的UITableViewController的Custom Class,Class设置为刚刚新建的UDTableViewController。

定义一个复用标识

static NSString * const reuseIdentifier = @"UDCell";

当前tableview注册UITableViewCell类并设置复用标识为上面的标识

- (void)viewDidLoad {

[super viewDidLoad];

[self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:reuseIdentifier];

// Uncomment the following line to preserve selection between presentations.

// self.clearsSelectionOnViewWillAppear = NO;

// Uncomment the following line to display an Edit button in the navigation bar for this view controller.

self.navigationItem.rightBarButtonItem=self.editButtonItem;

}

采用复用的cell,并设置显示内容

- (NSInteger)numberOfSectionsInTableView:(UITableView*)tableView {

// Return the number of sections.

return 1;

}

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

// Return the number of rows in the section.

return 20;

}

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

UITableViewCell*cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier forIndexPath:indexPath];

cell.textLabel.text= [NSString stringWithFormat:@"%ld", indexPath.row];

// Configure the cell...

returncell;

}

现在看起来是这个样子:



正常状态

编辑状态

现在怎么让UITableView编辑时为多选呢?

那就是实现UITableView的代理方法

- (UITableViewCellEditingStyle)tableView:(UITableView*)tableView editingStyleForRowAtIndexPath:(NSIndexPath*)indexPath;

UITableViewCellEditingStyle为编辑状态, 声明如下:

typedefNS_ENUM(NSInteger, UITableViewCellEditingStyle) {

UITableViewCellEditingStyleNone, //无

UITableViewCellEditingStyleDelete,//删除状态

UITableViewCellEditingStyleInsert//插入状态

};

而多选就是UITableViewCellEditingStyleDelete、UITableViewCellEditingStyleInsert两者的组合。

所以返回状态如下:

- (UITableViewCellEditingStyle)tableView:(UITableView*)tableView editingStyleForRowAtIndexPath:(NSIndexPath*)indexPath

{

return UITableViewCellEditingStyleDelete | UITableViewCellEditingStyleInsert;

}

现在可以多选了,效果图:



多选

下面的方法为提交编辑时响应的方法,比如:删除状态下点击cell右边的删除按钮时;插入状态下点击左侧添加按钮时。编辑状态下并不会调用此方法,所以只能取其它的办法。

- (void)tableView:(UITableView*)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath*)indexPath


怎么保存多选的row呢?

如果要保存多选的row,我有一个方法(如果你有更好的方法,请告诉我

0 0
原创粉丝点击