ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [ios - Swift] UITableView Swipe Button 만들기
    ios 2020. 11. 20. 20:00

     

     

     

     

    1. leadingSwipeActionsConfigurationForRowAt, trailingSwipeActionsConfigurationForRowAt

    leadingSwipeActionsConfigurationForRowAt : 행의 앞 가장자리에서 표시할 스와이프 동작입니다.

    trailingSwipeActionsConfigurationForRowAt : 행의 끝 가장자리에서 표시할 스와이프 동작입니다.

     

    우리는 위 두 가지의 델리게이트를 이용하도록 하겠습니다.

     

    func tableView(_ tableView: UITableView, leadingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
        return nil
    }
    
    func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {        
        return nil
    }

     

     

     

     

    2. UIContextualAction, UISwipeActionsConfiguration

     

    이제 스와이프 델리게이트가 발생하면 표시할 작업을 정의해야 합니다. 

     

    아래와 같이 추가해주세요.

     

    func tableView(_ tableView: UITableView, leadingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
    
       let mute = UIContextualAction(style: .normal, title: nil) { (action, view, completionHandler) in
           completionHandler(true)
       }
    
       mute.accessibilityFrame = CGRect(x: 0, y: 0, width: 30, height: tableView.rowHeight)
       mute.backgroundColor = UIColor.blue
       mute.image = UIImage(systemName: "pencil.circle")
    
       let config = UISwipeActionsConfiguration(actions: [mute])
    
       return config
    }

     

    func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
    
        let hide = UIContextualAction(style: .normal, title: "숨김") { (action, view, completionHandler) in
            completionHandler(true)
        }
    
        // weak self : 클로져 내부에서 self 를 사용할 때 strong reference cycle 예방
        let delete = UIContextualAction(style: .normal, title: "차단") { [weak self] action, view, completionHandler in
    
            // 삭제 처리
            self!.members[indexPath.section].Members.remove(at: indexPath.row)
            tableView.deleteRows(at: [indexPath], with: .automatic)
            completionHandler(true)
        }
    
        hide.backgroundColor = .gray
        delete.backgroundColor = .orange
    
        let config = UISwipeActionsConfiguration(actions: [delete, hide])
        return config
    }

     

    UISwipeActions에 대한 동작은 클로져 내에서 진행하면 됩니다.

     

    UISwipeActions에 대한 값을 UISwipeActionsConfiguration에 배열 형태로 넣어준 후 실행해보면 아래와 같이 동작하는 것을 확인할 수 있습니다.

     

     

     

     

    행을 스와이프 하니 계속 늘어나는 걸 확인할 수 있는데 계속 늘리기 싫다면 위의 config의 설정을 바꿔야 합니다. 

     

    아래와 같이 추가해주세요.

     

    let config = UISwipeActionsConfiguration(actions: [delete, hide])
    // 끝까지 안늘어나게 함
    config.performsFirstActionWithFullSwipe = false
    
    return config

     

     

    이제 스와이프 버튼 구현을 마무리했습니다.

    댓글

Designed by Tistory.