[swift] RxDataSources에서 사용할 헤더 및 푸터 구성 방법

RxDataSources는 RxSwift의 확장 패키지로서 TableView 및 CollectionView의 데이터 소스를 쉽게 관리할 수 있게 해줍니다. 이 패키지를 사용하면 TableView 또는 CollectionView의 헤더와 푸터를 쉽게 구성할 수 있습니다. 이 글에서는 RxDataSources를 사용하여 TableView 또는 CollectionView의 헤더 및 푸터를 구성하는 방법에 대해 알아보겠습니다.

헤더 및 푸터 모델 생성

헤더나 푸터의 모양과 내용을 결정하기 위해 헤더 및 푸터 모델을 생성해야 합니다. 이 모델은 보통 클래스나 구조체로 생성되며 실제 뷰에 표시될 데이터를 포함합니다.

struct SectionHeader {
    let title: String
    let subtitle: String
}

struct SectionFooter {
    let count: Int
}

위의 코드에서는 헤더에는 titlesubtitle이라는 두 가지 속성이 있고, 푸터에는 count라는 속성이 있습니다. 이러한 속성은 실제로 뷰에서 사용될 데이터를 나타내는 예시입니다.

헤더 및 푸터용 템플릿 생성

RxDataSources에서는 헤더 및 푸터의 모양을 결정하는 템플릿을 생성해야 합니다. 이는 각각 CollectionViewSectionedDataSource.SupplementaryViewFactory를 사용하여 작성됩니다.

let headerTemplate: CollectionViewSectionedDataSource<SectionModel<String, ItemModel>>.SupplementaryViewFactory = { collectionView, kind, indexPath in
    guard let headerView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "HeaderView", for: indexPath) as? HeaderView else {
        fatalError("Failed to dequeue reusable header view")
    }

    // 헤더에 데이터 설정
    let section = sections[indexPath.section]
    let header = section.model
    headerView.titleLabel.text = header.title
    headerView.subtitleLabel.text = header.subtitle

    return headerView
}

let footerTemplate: CollectionViewSectionedDataSource<SectionModel<String, ItemModel>>.SupplementaryViewFactory = { collectionView, kind, indexPath in
    guard let footerView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "FooterView", for: indexPath) as? FooterView else {
        fatalError("Failed to dequeue reusable footer view")
    }

    // 푸터에 데이터 설정
    let section = sections[indexPath.section]
    let footer = section.model
    footerView.countLabel.text = "\(footer.count)개"

    return footerView
}

위의 코드에서는 headerTemplatefooterTemplate을 각각 작성하였습니다. headerTemplateHeaderView를 사용하여 헤더를 구성하고, footerTemplateFooterView를 사용하여 푸터를 구성합니다. 각 템플릿에서는 데이터를 설정하고, 해당 헤더나 푸터 뷰를 반환해야 합니다.

데이터 소스에 헤더 및 푸터 적용

마지막으로, 데이터 소스를 생성하고 앞에서 작성한 헤더 및 푸터 템플릿을 적용해야 합니다.

let dataSource = RxCollectionViewSectionedReloadDataSource<SectionModel<String, ItemModel>>(
    configureCell: { dataSource, collectionView, indexPath, item in
        // 셀 구성
    },
    configureSupplementaryView: { dataSource, collectionView, kind, indexPath in
        if kind == UICollectionView.elementKindSectionHeader {
            return headerTemplate(collectionView, kind, indexPath)
        } else {
            return footerTemplate(collectionView, kind, indexPath)
        }
    }
)

위의 코드에서는 RxCollectionViewSectionedReloadDataSource를 사용하여 데이터 소스를 생성하고, configureSupplementaryView 클로저를 사용하여 헤더 또는 푸터가 필요한 경우 템플릿을 호출하도록 설정했습니다.

결론

이제 RxDataSources를 사용하여 TableView 또는 CollectionView에서 헤더와 푸터를 쉽게 구성하는 방법을 알아보았습니다. 헤더와 푸터에 대한 모델과 템플릿을 생성하고, 데이터 소스에 적용하여 원하는 동작과 외관을 가진 뷰를 구성할 수 있습니다.

참고 자료