iOS11 UITableViewCell滑動事件改動

在iOS8以後,蘋果官方增長了UITableView的右滑操做接口swift

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

在這個方法中能夠定義所須要的操做按鈕(刪除、置頂等),這些按鈕的類就是UITableViewRowAction。這個類定義按鈕的顯示文字、背景色和事件。而且返回數組的第一個元素在UITableViewCell的最右側顯示,最後一個元素在最左側顯示。數組

image.png

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中新增了兩個代理方法ide

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

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

// 左側按鈕自定義
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.png

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

相關文章
相關標籤/搜索