iOS/Swift

Swift) TableView Swipe

Brad_Heo 2022. 8. 20. 21:44

TableView Swipe

삭제나 편집을 위한 이벤트를 Swipe를 통해 구현해보자

TableViewleadingSwipeActionsConfigurationForRowAt, trailingSwipeActionsConfigurationForRowAt 활용
|왼쪽으로 Swipe|여러 개의 item|
|:---:|:---:|
|||

왼쪽 Swipe 적용

코드

TableView leadingSwipeActionsConfigurationForRowAt를 통해 해당 셀에 대한 이벤트를 구현할 수 있었다.

func tableView(_ tableView: UITableView, leadingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
        let editAction = UIContextualAction(style: .normal, title: "편집") { (UIContextualAction, UIView, success: @escaping (Bool) -> Void) in
            success(true)
        }
        editAction.backgroundColor = .systemGreen

        return UISwipeActionsConfiguration(actions: [editAction])
    }

오른쪽 Swipe 적용

코드

TableView trailingSwipeActionsConfigurationForRowAt를 통해 해당 셀에 대한 이벤트를 구현할 수 있었다.


func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
        let item = models[indexPath.row]
        let deleteAction = UIContextualAction(style: .normal, title: "삭제") { (UIContextualAction, UIView, success: @escaping (Bool) -> Void) in
            self.deleteItem(item: item)
            success(true)
        }
        deleteAction.backgroundColor = .systemRed

        return UISwipeActionsConfiguration(actions: [deleteAction])
    }

여러개 item 추가

func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
        let item = models[indexPath.row]
        let deleteAction = UIContextualAction(style: .normal, title: "삭제") { (UIContextualAction, UIView, success: @escaping (Bool) -> Void) in
            self.deleteItem(item: item)
            success(true)
        }
        deleteAction.backgroundColor = .systemRed

        let editAction = UIContextualAction(style: .normal, title: "편집") { (UIContextualAction, UIView, success: @escaping (Bool) -> Void) in
            success(true)
        }
        editAction.backgroundColor = .systemGreen

        return UISwipeActionsConfiguration(actions: [deleteAction, editAction])
    }

'iOS > Swift' 카테고리의 다른 글

Swift) SwiftLint 적용  (0) 2022.09.10
Swift) DatePicker  (0) 2022.09.10
Swift) Localize  (0) 2022.08.18
Swift) UIRefreshControl 사용  (0) 2022.08.03
Swift) iOS 메모리 영역 확인하기(Stack)  (0) 2022.07.25