[swift] Swift Koloda를 사용하여 카드 스와이프 후 인덱스 업데이트하기

Koloda는 Swift로 작성된 카드 스와이프 라이브러리로, 사용자가 카드를 스와이프하면 새로운 카드로 업데이트할 수 있는 기능을 제공합니다. 이번 예제에서는 Koloda를 사용하여 카드를 스와이프하는 동작 후 인덱스를 업데이트하는 방법을 알아보겠습니다.

Koloda 라이브러리 설치하기

먼저, Koloda 라이브러리를 프로젝트에 추가해야 합니다. 이를 위해 CocoaPods를 사용할 수 있습니다. Podfile에 다음과 같이 Koloda를 추가하고, 터미널에서 pod install 명령어를 실행하세요.

// Podfile
platform :ios, '11.0'
target 'YourProjectName' do
  use_frameworks!
  pod 'Koloda'
end

카드 덱 생성하기

Koloda를 사용해서 카드 스와이프를 구현하기 전에, 카드 덱을 만들어야 합니다. 이 예제에서는 간단한 문자열을 담은 카드 덱을 생성하겠습니다. ViewController.swift 파일을 열고, 다음과 같이 코드를 작성하세요:

// ViewController.swift

import UIKit
import Koloda

class ViewController: UIViewController {
  
  @IBOutlet weak var kolodaView: KolodaView!
  
  let cardDeck = ["Card 1", "Card 2", "Card 3", "Card 4", "Card 5"]

  override func viewDidLoad() {
    super.viewDidLoad()
    
    kolodaView.delegate = self
    kolodaView.dataSource = self
  }
}

// KolodaViewDelegate와 KolodaViewDataSource 프로토콜 구현하기

extension ViewController: KolodaViewDelegate, KolodaViewDataSource {
  
  func kolodaNumberOfCards(_ koloda: KolodaView) -> Int {
    return cardDeck.count
  }
  
  func koloda(_ koloda: KolodaView, viewForCardAt index: Int) -> UIView {
    let cardView = UIView(frame: koloda.bounds)
    cardView.backgroundColor = .white
    
    let label = UILabel(frame: cardView.bounds)
    label.text = cardDeck[index]
    label.textAlignment = .center
    label.font = UIFont.systemFont(ofSize: 24)
    cardView.addSubview(label)
    
    return cardView
  }
  
  // 카드가 스와이프되었을 때 실행되는 메소드
  func kolodaDidSwiped(_ koloda: KolodaView, card: DraggableCardView, in direction: SwipeResultDirection) {
    if direction == .left {
      print("카드를 왼쪽으로 스와이프 했습니다.")
    } else if direction == .right {
      print("카드를 오른쪽으로 스와이프 했습니다.")
    }
    
    // 인덱스 업데이트하기
    let currentIndex = kolodaView.currentCardIndex
    let nextIndex = currentIndex + 1
    
    print("현재 카드 인덱스: \(currentIndex)")
    print("다음 카드 인덱스: \(nextIndex)")
  }
}

위의 예제 코드에서, cardDeck 배열은 사용할 카드의 내용을 담고 있습니다. koloda(_:viewForCardAt:) 메소드는 카드 뷰를 생성하고, 해당 카드에 텍스트를 표시하는 역할을 합니다.

kolodaDidSwiped(_:card:in:) 메소드는 카드가 스와이프되면 실행되는 메소드입니다. 여기서는 카드가 왼쪽으로 스와이프되었는지 오른쪽으로 스와이프되었는지를 확인하고, 인덱스를 업데이트하는 기능을 추가하였습니다.

이제 앱을 실행하고 카드를 스와이프하면 인덱스가 업데이트되는 것을 확인할 수 있습니다.

결론

Koloda 라이브러리를 사용하여 카드 스와이프 후 인덱스를 업데이트하는 방법에 대해 알아보았습니다. 이를 통해 사용자가 카드를 스와이프하고 다음 카드로 이동하는 기능을 구현할 수 있습니다.