UITableView左右滑动删除常见问题

来源:互联网 发布:济溪环境交流网络 编辑:程序博客网 时间:2024/06/06 08:48

iOS中的UITableView,在上面滑动时,可以出现一个“删除”按钮,来进行删除操作。
大概以有下几个要素:

1.UITableViewDelegate中的下面一个方法:
  1. - (UITableViewCellEditingStyle)tableView: (UITableView *)tableView editingStyleForRowAtIndexPath: (NSIndexPath *)indexPath; 

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

2- (BOOL)tableViewUITableView *)tableView canMoveRowAtIndexPathNSIndexPath *)indexPath; 

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

3.-(void)tableViewUITableView *)tableView commitEditingStyleUITableViewCellEditingStyle)editingStyle forRowAtIndexPathNSIndexPath *)indexPath; 
返回你想显示的文本就可以了。 

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

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

小技巧:如果感觉“删除”两个字太呆板,可以自定义这个按钮的显示文字的,需要实现UITableViewDelegate的如下方法:
  1. - (NSString *)tableViewUITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPathNSIndexPath *)indexPath 
0 0
原创粉丝点击