[swift] IGListKit에서 새로운 데이터 업데이트 시 애니메이션 설정하는 방법

IGListKit는 iOS 앱에서 복잡한 데이터 표시 및 업데이트를 처리하는 데 도움이되는 강력한 프레임 워크입니다. IGListKit을 사용하여 데이터를 업데이트 할 때 애니메이션을 추가하고 싶다면, 다음과 같은 방법을 사용할 수 있습니다.

1. 애니메이션을 지원하는 데이터 타입 사용

IGListKit은 ListDiffable 프로토콜을 준수하는 데이터 타입을 사용하여 데이터 업데이트를 처리합니다. 따라서 애니메이션을 지원하려면 데이터 타입이 ListDiffable을 준수해야합니다.

class MyData: NSObject, ListDiffable {
    let identifier: String
    let value: Int
    
    init(identifier: String, value: Int) {
        self.identifier = identifier
        self.value = value
    }
    
    func diffIdentifier() -> NSObjectProtocol {
        return identifier as NSObjectProtocol
    }
    
    func isEqual(toDiffableObject object: ListDiffable?) -> Bool {
        guard let other = object as? MyData else { return false }
        return value == other.value
    }
}

위의 예시에서 MyData 클래스는 ListDiffable 프로토콜을 준수하고 있습니다. diffIdentifier() 메서드는 데이터 객체를 고유하게 식별하는 데 사용되며, isEqual(toDiffableObject:) 메서드는 데이터 객체가 같은지 비교합니다.

2. IGListBindingSectionController 사용

IGListBindingSectionController를 사용하면 데이터 업데이트를 처리하고 애니메이션을 설정할 수 있습니다. 업데이트를 수행하는 메서드 내에서 애니메이션을 설정하는 방법은 다음과 같습니다.

class MySectionController: ListBindingSectionController<MyData>, ListBindingSectionControllerDataSource {
    
    override init() {
        super.init()
        dataSource = self
    }
    
    // MARK: - ListBindingSectionControllerDataSource
    
    func sectionController(_ sectionController: ListBindingSectionController<ListDiffable>, viewModelsFor object: Any) -> [ListDiffable] {
        guard let data = object as? MyData else { return [] }
        return [data]
    }
    
    func sectionController(_ sectionController: ListBindingSectionController<ListDiffable>, cellForViewModel viewModel: Any, at index: Int) -> UICollectionViewCell {
        // 셀을 반환하는 코드
    }
    
    func sectionController(_ sectionController: ListBindingSectionController<ListDiffable>, sizeForViewModel viewModel: Any, at index: Int) -> CGSize {
        // 셀 크기를 반환하는 코드
    }
    
    // MARK: - ListBindingSectionControllerDelegate
    
    override func didUpdate(to object: Any) {
        super.didUpdate(to: object)
        // 데이터 업데이트 시 애니메이션 설정
        update(animated: true, completion: nil)
    }
}

위의 예시에서 MySectionControllerListBindingSectionController<MyData>를 상속 받은 구현체입니다. sectionController(_:viewModelsFor:) 메서드에서 데이터를 처리하고, sectionController(_:cellForViewModel:at:)sectionController(_:sizeForViewModel:at:) 메서드에서 셀을 반환하고 크기를 설정합니다.

didUpdate(to:) 메서드에서 데이터가 업데이트 될 때 마다 update(animated:completion:) 메서드를 호출하여 애니메이션을 설정합니다.

3. 데이터 업데이트하기

데이터 업데이트 시에는 IGListAdapterperformUpdates(animated:completion:) 메서드를 사용합니다.

// 데이터 업데이트
adapter.performUpdates(animated: true, completion: nil)

위의 예시에서 adapterIGListAdapter 인스턴스입니다. performUpdates(animated:completion:) 메서드를 호출하여 데이터를 업데이트하고 애니메이션을 적용합니다.

위의 방법을 따라 IGListKit에서 새로운 데이터 업데이트 시 애니메이션을 설정할 수 있습니다. IGListKit의 다양한 기능을 활용하여 앱의 사용자 인터페이스를 더 동적이고 흥미롭게 만들 수 있습니다.

참고 자료