project/Kuring(공지알림)

iOS UITableViewCell Swipe Action 구현하기

lgvv 2022. 5. 5. 14:11

iOS UITableViewCell Swipe Action 구현하기

 

카카오톡 처럼 SwipeAction 기능을 활용하려고 함.

애플 문서를 정독하고, 포스팅에는 적용 위주로 기술.

 

목차

1. tableView에서 leading과 trailing swipe를 지원해주는 메서드를 사용해 구현

2. editStyle을 메소드를 활용하여 구현

 

 

1. tableView에서 leading과 trailing swipe를 지원해주는 메서드를 사용해 구현

코드에 대한 변수를 선언.

completionHandler(true)는 버튼을 클릭하면 액션이 완료되었음을 알려야, UI에서 사라진다.

즉, 애플 시스템에 Completion 받게해서 완료 처리하는 것.

 

    func tableView(_ tableView: UITableView, leadingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
        // TODO: 추후에 공지 보관함 기능 추가
        let subscribeAction = UIContextualAction(
            style: .normal,
            title: nil
        ) {
            action, view, completionHandler in
            completionHandler(true)
        }
        subscribeAction.backgroundColor = .systemYellow
        subscribeAction.image = UIImage(systemName: "archivebox.fill")
        
        return UISwipeActionsConfiguration(actions: [subscribeAction])
    }

 

 

 

 

스크린샷

노란색 저 부분!!

 


2. editStyle을 메소드를 활용하여 구현

위와 같지만 다른 구현이다.

    func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCell.EditingStyle {
        return .delete
    }
    
    func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
        switch editingStyle {
        case .delete:
            tableView.beginUpdates()
            lockerNotices.remove(at: indexPath.row)
            tableView.deleteRows(at: [indexPath], with: .fade)
            tableView.endUpdates()
        default:
            break
        }
    }

delete