[swift] RxDataSources를 사용한 컬렉션 뷰의 다른 레이아웃 구성 방법

RxDataSources는 iOS 앱 개발을 위한 ReactiveX 기반의 데이터 소스 라이브러리입니다. 이 라이브러리를 사용하면 UICollectionView와 같은 컬렉션 뷰의 데이터 소스를 쉽게 관리할 수 있습니다.

이번 포스트에서는 RxDataSources를 사용하여 컬렉션 뷰의 다른 레이아웃 구성 방법에 대해 알아보겠습니다.

1. RxDataSources 설치하기

RxDataSources를 사용하기 위해서는 CocoaPods와 같은 의존성 관리 도구를 사용하여 프로젝트에 설치해야 합니다.

먼저, Podfile에 다음과 같이 RxDataSources를 추가합니다.

pod 'RxDataSources'

그런 다음, 터미널에서 pod install 명령어를 실행하여 RxDataSources를 설치합니다.

2. 다른 레이아웃 타입 정의하기

RxDataSources를 사용하여 다른 레이아웃을 구성하기 위해서는 레이아웃 타입을 먼저 정의해야 합니다.

레이아웃 타입은 다음과 같이 정의할 수 있습니다.

enum LayoutType {
    case grid
    case list
}

3. 다른 레이아웃에 따른 셀 디자인 및 데이터 소스 설정하기

레이아웃에 따라 컬렉션 뷰의 셀 디자인과 데이터 소스를 설정해야 합니다.

다음은 그리드 레이아웃과 리스트 레이아웃에 따른 셀 디자인 및 데이터 소스 설정하는 예제입니다.

struct GridItem: IdentifiableType, Equatable {
    let id: String
    let title: String
    // 그리드 셀에 표시할 데이터 모델
}

struct ListItem: IdentifiableType, Equatable {
    let id: String
    let title: String
    // 리스트 셀에 표시할 데이터 모델
}

extension GridItem: RxCollectionViewSectionedReloadDataSourceType {
    typealias SectionModel = SectionModel<String, GridItem>
    
    var identity: String {
        return id
    }
    
    init(original: GridItem, items: [GridItem]) {
        self = original
    }
}

extension ListItem: RxCollectionViewSectionedReloadDataSourceType {
    typealias SectionModel = SectionModel<String, ListItem>
    
    var identity: String {
        return id
    }
    
    init(original: ListItem, items: [ListItem]) {
        self = original
    }
}

위의 예제에서는 같은 모델 타입을 사용하지만, 다른 레이아웃에 따라 다른 식별자를 가지게 됩니다.

4. 레이아웃에 따른 컬렉션 뷰 화면 구성하기

다음은 레이아웃에 따라 컬렉션 뷰의 화면을 구성하는 예시 코드입니다.

let collectionView = UICollectionView(frame: self.view.bounds, collectionViewLayout: UICollectionViewFlowLayout())
self.view.addSubview(collectionView)

let items = Observable.of([
    SectionModel(model: "Grid", items: [GridItem(id: "1", title: "Item 1"), GridItem(id: "2", title: "Item 2"), ...]),
    SectionModel(model: "List", items: [ListItem(id: "1", title: "Item 1"), ListItem(id: "2", title: "Item 2"), ...])
])

let dataSource = RxCollectionViewSectionedReloadDataSource<SectionModel<String, IdentifiableType>>(
    configureCell: { dataSource, collectionView, indexPath, item in
        if dataSource[indexPath] is GridItem {
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "GridCell", for: indexPath) as! GridCell
            cell.configure(with: item as! GridItem)
            return cell
        } else {
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ListCell", for: indexPath) as! ListCell
            cell.configure(with: item as! ListItem)
            return cell
        }
    }
)

items
    .bind(to: collectionView.rx.items(dataSource: dataSource))
    .disposed(by: disposeBag)

위의 예시 코드에서는 RxDataSources의 RxCollectionViewSectionedReloadDataSource를 사용하여 컬렉션 뷰의 데이터 소스를 설정하고, configureCell 클로저에서 레이아웃에 따라 다른 셀을 생성하도록 하였습니다. GridCellListCell은 각각 그리드 셀과 리스트 셀을 나타내는 커스텀 셀입니다.

5. 결론

위에서 살펴본 예제를 통해 RxDataSources를 사용하여 컬렉션 뷰의 다른 레이아웃을 구성하는 방법을 알아보았습니다. RxDataSources를 사용하면 컬렉션 뷰의 데이터 소스 관리를 훨씬 간편하게 할 수 있으며, 다양한 레이아웃에 대응하는 기능을 구현할 수 있습니다.