UITableView左右滑动cell无法显示“删除”按钮的原因分析

来源:互联网 发布:图书馆管理数据库设计 编辑:程序博客网 时间:2024/05/22 15:54
iOS中的UITableView,在上面滑动时,可以出现一个“删除”按钮,来进行删除操作。
但是,有些时候,由于实现方法不对,滑动时,这个按钮却显示不出来。分析了一下原因,大概以有下几个要素:


1.UITableViewDelegate中的下面一个方法:
  1. // Allows customization of the editingStyle for a particular cell located at 'indexPath'. If not implemented, all editable cells will have UITableViewCellEditingStyleDelete set for them when the table has editing property set to YES.
  2. - (UITableViewCellEditingStyle)tableView: (UITableView *)tableView editingStyleForRowAtIndexPath: (NSIndexPath *)indexPath;
复制代码

这个方法可以不实现,默认会是响应滑动手势,显示“删除”按钮的效果。如果实现的话,一定要返回类型:UITableViewCellEditingStyleDelete。否则在cell上左右滑动时,不会出现“删除”按钮。

2.UITableViewDataSource中的下面两个方法:
  1. // Allows the reorder accessory view to optionally be shown for a particular row. By default, the reorder control will be shown only if the datasource implements -tableView:moveRowAtIndexPath:toIndexPath:
  2. - (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath;
复制代码

这个方法表示判断对应的indexPath的cell是否可以编辑。可以不实现,默认是可以编辑的,如果实现的话,一定要返回YES。否则出不来“删除”按钮。

  1. - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath;
复制代码

这个方法一定要实现,因为系统会判断你是否实现了这个方法,只有实现了这个方法,在cell上左右滑动时才会出现“删除”按钮。

总之,正确实现上面三个方法,“删除”按钮应该会显示出来。
还要别忘了指定tableView的dataSource和delegate啊,不然一切都是白费的。

小技巧:如果感觉“删除”两个字太呆板,可以自定义这个按钮的显示文字的,需要实现UITableViewDelegate的如下方法:
  1. - (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath NS_AVAILABLE_IOS(3_0);
复制代码

返回你想显示的文本就可以了。

原文链接:http://bluevt.org/?p=216
0 0
原创粉丝点击