[swift] IGListKit에서 셀의 타입과 데이터 연결하는 방법

IGListKit은 iOS 앱에서 컬렉션뷰를 구성하기 위한 강력한 프레임워크입니다. IGListKit을 사용하면 컬렉션뷰의 데이터 소스 및 UI 관리를 간편하게 할 수 있습니다.

여기서는 IGListKit을 사용하여 셀의 타입과 데이터를 연결하는 방법에 대해 알아보겠습니다.

셀의 타입과 클래스 생성

먼저, 각 셀마다 대응되는 셀 클래스를 생성해야 합니다. 예를 들어, 책 정보를 보여주는 BookCell 클래스를 만들어 보겠습니다.

class BookCell: UICollectionViewCell {
    // 필요한 UI 요소들을 추가해주세요
}

ListItem 클래스 만들기

다음으로, 각 셀에 표시할 데이터를 담은 ListItem 클래스를 만들어야 합니다. BookCell과 연결된 ListItem을 만들어 보겠습니다.

class BookItem: NSObject {
    let title: String
    let author: String

    init(title: String, author: String) {
        self.title = title
        self.author = author
    }
}

ListAdapter 생성하기

이제, IGListKit의 ListAdapter를 생성하여 컬렉션뷰와 데이터를 연결해야 합니다. ListAdapter는 컬렉션뷰에 데이터를 제공하고 관리하는 역할을 합니다.

import IGListKit

class ViewController: UIViewController, ListAdapterDataSource {

    let adapter = ListAdapter(updater: ListAdapterUpdater(), viewController: self)
    let collectionView = UICollectionView(frame: .zero, collectionViewLayout: UICollectionViewFlowLayout())

    var items: [ListItem] = []

    override func viewDidLoad() {
        super.viewDidLoad()

        collectionView.backgroundColor = .white
        view.addSubview(collectionView)
        adapter.collectionView = collectionView
        adapter.dataSource = self
    }
  
    // MARK: - ListAdapterDataSource
  
    func objects(for listAdapter: ListAdapter) -> [ListDiffable] {
        return items
    }
  
    func listAdapter(_ listAdapter: ListAdapter, sectionControllerFor object: Any) -> ListSectionController {
        return ListSectionController()
    }
  
    func emptyView(for listAdapter: ListAdapter) -> UIView? {
        return nil
    }
  
}

ListSectionController 구현하기

마지막으로, ListAdapterDataSource에 구현한 ListSectionController에서 셀의 타입과 데이터를 설정해야 합니다. 즉, 셀을 생성하고 데이터를 바인딩하는 로직을 작성해야 합니다.

import IGListKit

class BookSectionController: ListSectionController {
  
    var item: ListItem?
  
    override func sizeForItem(at index: Int) -> CGSize {
        // 셀의 크기를 설정해주세요
        return CGSize(width: collectionContext?.containerSize.width ?? 0, height: 100)
    }
  
    override func cellForItem(at index: Int) -> UICollectionViewCell {
        guard let context = collectionContext else { return UICollectionViewCell() }
      
        // BookCell을 생성하고 데이터를 설정해주세요
        let cell = context.dequeueReusableCell(of: BookCell.self, for: self, at: index)
        
        if let bookCell = cell as? BookCell, let item = item {
            // bookCell에 item 데이터를 바인딩해주세요
            bookCell.titleLabel.text = item.title
            bookCell.authorLabel.text = item.author
        }
        
        return cell
    }

    override func didUpdate(to object: Any) {
        guard let item = object as? ListItem else { return }
        self.item = item
    }
  
}

이제 IGListKit을 사용하여 셀의 타입과 데이터를 연결하는 방법에 대해 알게 되었습니다. IGListKit은 컬렉션뷰를 관리하는 많은 기능을 제공하므로, 앱의 컬렉션뷰 관련 작업을 보다 간결하고 효율적으로 처리할 수 있게 도와줍니다.

참고 자료: IGListKit GitHub 리포지터리