project/Kuring(공지알림)
[iOS] tableViewCell Swipe Action 구현하기
lgvv
2022. 5. 5. 14:11
tableViewCell Swipe Action 구현하기
✅ 이번 시간에는 tableViewCell Swipe Action을 구현해보자
직접 애플 문서를 읽어보는 것을 추천하지만, 이 포스팅에서는 정말 간략하게 어떻게 사용하는 지만 알아보자.
이번 포스팅에서는
1. tableView에서 leading과 trailing swipe를 지원해주는 메소드를 사용하여 구현하는 것
2. editStyle을 메소드를 활용하여 구현하는 것
을 볼 예정이다.
✅ 1. tableView에서 leading과 trailing swipe를 지원해주는 메소드를 사용하여 구현하는 것
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])
}
코드에 대한 변수를 선언한다.
completionHandler(true) 이 코드는 액션 버튼을 클릭하면 액션이 사라져야겠지?
그 부분을 처리해주는 코드이다.
✅ UI 예시
✅ 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
}
}