iOS 11 Table View Cell 滑动事件按钮自定义
2017-06-08 本文已影响4703人
冰霜海胆
在 iOS 11 之前,我们使用:
func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]?
来对Cell
的滑动手势出现的按钮进行自定义。
如下图:
func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
let deleteAction = UITableViewRowAction(style: .destructive, title: "删除") { (action, indexPath) in
self.titles.remove(at: indexPath.row)
tableView.deleteRows(at: [indexPath], with: .left)
}
let archiveAction = UITableViewRowAction(style: .normal, title: "归档") { (action, indexPath) in
}
return [deleteAction, archiveAction]
}
而在 iOS 11 之前,非常希望能实现系统那样直接一滑到底删除某个
Cell
的效果。
现在,从 iOS 11 开始提供了新的代理方法,并且在未来将要取代
func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]?
这个用了很久的方法。
新的方法提供了:左侧按钮自定义、右侧按钮自定义、自定义图片、背景颜色,通过 UIContextualAction
来设置。
// 左侧按钮自定义
func tableView(_ tableView: UITableView, leadingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
let leftAction = UIContextualAction(style: .normal, title: "左侧") { (action, view, finished) in
finished(true)
}
return UISwipeActionsConfiguration(actions: [leftAction])
}
// 右侧按钮自定义
func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
let deleteAction = UIContextualAction(style: .destructive, title: "删除") { (action, view, finished) in
self.titles.remove(at: indexPath.row)
tableView.deleteRows(at: [indexPath], with: .automatic)
// 回调告知执行成功,否则不会删除此行!!!
finished(true)
}
let archiveAction = UIContextualAction(style: .normal, title: "归档") { (action, view, finished) in
}
return UISwipeActionsConfiguration(actions: [deleteAction, archiveAction])
}
Objective-C
- (nullable UISwipeActionsConfiguration *)tableView:(UITableView *)tableView trailingSwipeActionsConfigurationForRowAtIndexPath:(NSIndexPath *)indexPath {
UIContextualAction *deleteAction = [UIContextualAction
contextualActionWithStyle:UIContextualActionStyleDestructive
title:@"删除"
handler:^(UIContextualAction * _Nonnull action,
__kindof UIView * _Nonnull sourceView,
void (^ _Nonnull completionHandler)(BOOL))
{
[self.titles removeObjectAtIndex:indexPath.row];
[self.tableView deleteRowsAtIndexPaths: [NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationAutomatic];
completionHandler(true);
}];
// 设置按钮图片
[deleteAction setImage:[UIImage imageNamed:@"Star"]];
NSArray *actions = [[NSArray alloc] initWithObjects:deleteAction, nil];
return [UISwipeActionsConfiguration configurationWithActions:actions];
}