[swift] Swift Koloda를 사용하여 카드 스와이프 제스처 설정하기

본 포스트에서는 Swift Koloda 라이브러리를 사용하여 iOS 앱에 카드 스와이프 제스처를 설정하는 방법을 알아보겠습니다.

Koloda는 카드 스와이프 기능을 제공하는 강력한 라이브러리입니다. 이를 사용하면 Tinder와 같은 카드 스와이프 기반의 앱을 쉽게 개발할 수 있습니다.

1. 프로젝트에 Swift Koloda 추가하기

먼저, CocoaPods를 사용하여 Swift Koloda를 프로젝트에 추가해야 합니다.

  1. Podfile 파일을 열고 다음 내용을 추가합니다.
pod 'Koloda'
  1. 터미널을 열고 프로젝트 디렉토리로 이동한 후 pod install 명령을 실행합니다.
$ pod install
  1. 프로젝트를 열고 import Koloda를 추가하여 Swift Koloda를 사용할 수 있습니다.

2. KolodaView 생성 및 제스처 설정

이제 KolodaView를 생성하고 카드 스와이프 제스처를 설정해보겠습니다.

import UIKit
import Koloda

class ViewController: UIViewController, KolodaViewDelegate, KolodaViewDataSource {

    @IBOutlet weak var kolodaView: KolodaView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        kolodaView.delegate = self
        kolodaView.dataSource = self
        
        let swipeRight = UISwipeGestureRecognizer(target: self, action: #selector(swipeRightAction))
        swipeRight.direction = .right
        kolodaView.addGestureRecognizer(swipeRight)
        
        let swipeLeft = UISwipeGestureRecognizer(target: self, action: #selector(swipeLeftAction))
        swipeLeft.direction = .left
        kolodaView.addGestureRecognizer(swipeLeft)
    }
    
    // 카드 수 설정
    func kolodaNumberOfCards(_ koloda: KolodaView) -> Int {
        return 10
    }
    
    // 카드 뷰 설정
    func koloda(_ koloda: KolodaView, viewForCardAt index: Int) -> UIView {
        let cardView = UIView()
        cardView.backgroundColor = .red
        return cardView
    }
    
    // 카드가 제스처에 따라 완전히 사라졌을 때 호출됨
    func koloda(_ koloda: KolodaView, didSwipeCardAt index: Int, in direction: SwipeResultDirection) {
        if direction == .right {
            print("Swiped right")
        } else if direction == .left {
            print("Swiped left")
        }
    }
    
    // 오른쪽 스와이프 제스처 액션
    @objc func swipeRightAction() {
        kolodaView.swipe(.right)
    }
    
    // 왼쪽 스와이프 제스처 액션
    @objc func swipeLeftAction() {
        kolodaView.swipe(.left)
    }
}

위의 코드에서 kolodaView는 Interface Builder를 통해 연결된 KolodaView 인스턴스입니다. kolodaView.delegatekolodaView.dataSource를 현재 클래스로 설정하여 일부 이벤트를 처리할 수 있도록 합니다. 또한 UISwipeGestureRecognizer를 사용하여 오른쪽 및 왼쪽 스와이프 제스처를 추가합니다.

kolodaNumberOfCards 함수에서는 카드의 수를 설정합니다. 이 예제에서는 10장의 카드가 있다고 가정합니다.

koloda(_:viewForCardAt:) 함수에서는 각각의 카드에 대한 뷰를 설정합니다. 이 예제에서는 빨간색으로 설정된 UIView를 사용합니다.

koloda(_:didSwipeCardAt:in:) 함수는 카드가 스와이프되었을 때 호출되는 함수입니다. 이 예제에서는 오른쪽으로 스와이프되었는지 왼쪽으로 스와이프되었는지에 따라 콘솔에 해당 메시지를 출력합니다.

마지막으로 swipeRightActionswipeLeftAction 함수는 각각 오른쪽 및 왼쪽 스와이프 제스처에 대한 액션 함수입니다. 각각 kolodaView.swipe(.right)kolodaView.swipe(.left)를 호출하여 카드를 스와이프합니다.

이제 iOS 앱에서 Swift Koloda를 사용하여 카드 스와이프 기능을 활용할 수 있습니다.

참고 자료