在 iOS 11 之前,我們使用:
func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]?
來對Cell
的滑動手勢出現(xiàn)的按鈕進(jìn)行自定義倦逐。
如下圖:
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 之前,非常希望能實(shí)現(xiàn)系統(tǒng)那樣直接一滑到底刪除某個
Cell
的效果牲证。
現(xiàn)在男窟,從 iOS 11 開始提供了新的代理方法,并且在未來將要取代
func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]?
這個用了很久的方法蒿囤。
新的方法提供了:左側(cè)按鈕自定義客们、右側(cè)按鈕自定義、自定義圖片材诽、背景顏色底挫,通過 UIContextualAction
來設(shè)置。
// 左側(cè)按鈕自定義
func tableView(_ tableView: UITableView, leadingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
let leftAction = UIContextualAction(style: .normal, title: "左側(cè)") { (action, view, finished) in
finished(true)
}
return UISwipeActionsConfiguration(actions: [leftAction])
}
// 右側(cè)按鈕自定義
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)
// 回調(diào)告知執(zhí)行成功脸侥,否則不會刪除此行=ǖ恕!睁枕!
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);
}];
// 設(shè)置按鈕圖片
[deleteAction setImage:[UIImage imageNamed:@"Star"]];
NSArray *actions = [[NSArray alloc] initWithObjects:deleteAction, nil];
return [UISwipeActionsConfiguration configurationWithActions:actions];
}