iOS11 UITableViewCell滑動事件改動

weixin_33830216發表於2018-01-03

在iOS8之後,蘋果官方增加了UITableView的右滑操作介面

optional func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]?
複製程式碼

在這個方法中可以定義所需要的操作按鈕(刪除、置頂等),這些按鈕的類就是UITableViewRowAction。這個類定義按鈕的顯示文字、背景色和事件。並且返回陣列的第一個元素在UITableViewCell的最右側顯示,最後一個元素在最左側顯示。

override func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
        let deleteAction = UITableViewRowAction.init(style: .destructive, title: "Delete") { (action, indexpath) in
            self.dataArray.removeObject(at: indexpath.row)
            tableView.deleteRows(at: [indexpath], with: .left)
        }
        let markAction = UITableViewRowAction.init(style: .normal, title: "Mark") { (action, indexpath) in
            
        }
        return [deleteAction, markAction]
}
複製程式碼

在iOS11中新增了兩個代理方法

- (UISwipeActionsConfiguration *)tableView:(UITableView *)tableView leadingSwipeActionsConfigurationForRowAtIndexPath:(NSIndexPath *)indexPath;
- (UISwipeActionsConfiguration *)tableView:(UITableView *)tableView trailingSwipeActionsConfigurationForRowAtIndexPath:(NSIndexPath *)indexPath;
複製程式碼

新的方法提供了:左側按鈕自定義、右側按鈕自定義、自定義圖片、背景顏色,通過 UIContextualAction 來設定

// 左側按鈕自定義
override func tableView(_ tableView: UITableView, leadingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
        let leftAction = UIContextualAction.init(style: .normal, title: "leftAction", handler: { (action, view, completionHandler) in
            completionHandler(true)
        })
        let configuration = UISwipeActionsConfiguration.init(actions: [leftAction])
        return configuration
}
// 右側按鈕自定義    
override func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
        // 刪除操作
        let deleteAction = UIContextualAction.init(style: .destructive, title: "delete", handler: { (action, view, completionHandler) in
            completionHandler(true)
        })
        // 給按鈕設定背景圖片
        deleteAction.image = UIImage.init(named: "icon_del")

        let addAction = UIContextualAction.init(style: .normal, title: "add") { (action, view, completionHandler) in
            
        }
        // 可以修改按鈕的背景色
        addAction.backgroundColor = UIColor.purple
        let configuration = UISwipeActionsConfiguration.init(actions: [deleteAction, addAction])
        return configuration
}
複製程式碼

建立UIContextualAction物件時,UIContextualActionStyle有兩種型別,如果是置頂、已讀等按鈕就使用。UIContextualActionStyleNormal型別,delete操作按鈕可使用UIContextualActionStyleDestructive型別,當使用該型別時,如果是左滑操作,一直向左滑動某個cell,會直接執行刪除操作,不用再點選刪除按鈕。

滑動操作還有一個需要注意的點,當cell高度較小時,會只顯示image,不顯示title,當cell高度夠大時,會同時顯示image和title。

相關文章