apple/RxSwift, ReactorKit

RxSwift 06 RxDataSources

lgvv 2021. 8. 19. 15:30

RxSwift 06 RxDataSources

RxSwift에서 RxDataSource라는게 있어서 공부해보고자 함.

 

컬렉션뷰에서 섹션이 여러개면 난이도가 확 올라가는데, 이것도 정말 어렵다

 

 

목차 

  • 설치하기
  • 섹션 만들기
  • 전체 코드 리뷰

 

설치하기

RxSwift를 사용하려면 cocoapod 을 통해 설치해야 함

pod 'RxDataSources'

 

 

섹션 만들기

아래처럼 선언하여 구성

struct MySection {
    var header : String
    var items: [Item]
}

extension MySection : AnimatableSectionModelType {
    init(original: MySection, items: [Int]) {
        self = original
        self.items = items
    }
    
    var identity: String {
        return header
    }
    // 셀에 들어갈 데이터 타입을 정해야 한다.
    typealias Item = Int
    
}

 

 

전체 코드 리뷰

//
//  ViewController05.swift
//  SnapKit_practice
//
//  Created by Hamlit Jason on 2021/08/19.
//

import Foundation
import UIKit
import RxSwift
import RxCocoa
import RxDataSources
import Then

class ViewController06 : UIViewController {
    
    let data = Observable<[String]>.just(["first","second","third",])
    
    let tableView = UITableView().then {
        $0.translatesAutoresizingMaskIntoConstraints = false
        $0.register(UITableViewCell.self, forCellReuseIdentifier: "Cell")
    }
    
    let updateButton = UIButton().then {
        $0.setTitle("버튼클릭해봐", for: .normal)
    }
    
    let disposeBag = DisposeBag()
    var dataSource: RxTableViewSectionedAnimatedDataSource<MySection>?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = .systemTeal
        addSubView()
        setLayout()
        
        //        _ = data.bind(to: tableView.rx.items(cellIdentifier: ViewController06Cell.identifier, cellType: ViewController06Cell.self)) { index, item, cell in
        //            print("cell")
        //            cell.img.image = UIImage(systemName: "ticket")
        //            cell.label.text = "view 6 item \(index)"
        //        }.disposed(by: disposeBag)
        
        let dataSource = RxTableViewSectionedAnimatedDataSource<MySection>(
            configureCell: { ds, tv, _, item in
                let cell = tv.dequeueReusableCell(withIdentifier: "Cell") ?? UITableViewCell(style: .default, reuseIdentifier: "Cell")
                cell.textLabel?.text = "Item \(item)"
                
                return cell
            },
            titleForHeaderInSection: { ds, index in
                return ds.sectionModels[index].header
            }
        )
        
        self.dataSource = dataSource
        
        let sections = [
            MySection(header: "First section", items: [
                1,
                2
            ]),
            MySection(header: "Second section", items: [
                3,
                4
            ])
        ]
        
        Observable.just(sections)
            .bind(to: tableView.rx.items(dataSource: dataSource))
            .disposed(by: disposeBag)
        
        tableView.rx.setDelegate(self)
            .disposed(by: disposeBag)
        
    } // viewDidLosad
}

extension ViewController06 : UITableViewDelegate {
    func setLayout() {
        tableView.snp.makeConstraints {
            $0.top.equalTo(0)
            $0.leading.equalTo(0)
            $0.trailing.equalTo(0)
            $0.bottom.equalTo(-200)
            //            $0.edges.equalTo(view)
            //                .inset(UIEdgeInsets(top: 0, left: 0, bottom: 200, right: 0))
        }
    }
    func addSubView() {
        view.addSubview(tableView)
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        guard let item = dataSource?[indexPath],
              // .. or section and customize what you like
              dataSource?[indexPath.section] != nil
        else {
            return 0.0
        }
        
        print("\(item) : height")
        return CGFloat(40 + item * 10)
    }
}


struct MySection {
    var header: String
    var items: [Item]
}

extension MySection : AnimatableSectionModelType {
    typealias Item = Int
    
    var identity: String {
        return header
    }
    
    init(original: MySection, items: [Item]) {
        self = original
        self.items = items
    }
}

 

 

코드에 대한 결과

 

'apple > RxSwift, ReactorKit' 카테고리의 다른 글

iOS RxDelegateProxy 만들어보기 #1  (0) 2022.01.12
iOS RxStarScream 총정리  (0) 2022.01.12
Ch13. Intermediate RxCocoa  (0) 2021.08.12
RxSwift Ch12. Beginning RxCocoa  (0) 2021.08.12
🐉 RxSwift 4Hour - Step3(Rx)  (0) 2021.07.18