[RxCocoa] CollectionView

RudinP·7일 전
0

Study

목록 보기
372/376
import UIKit
import RxSwift
import RxCocoa

class RxCocoaCollectionViewViewController: UIViewController {
    
    let bag = DisposeBag()
    
    @IBOutlet weak var listCollectionView: UICollectionView!
    
    //#1. 바인딩할 옵저버블 생성
    let colorObservable = Observable.of(MaterialBlue.allColors)
    
    override func viewDidLoad() {
        super.viewDidLoad()
        //#2. 컬렉션뷰에 바인딩. 주로 identifier와 cellType 전달 메소드 사용
        colorObservable.bind(to: listCollectionView.rx.items(cellIdentifier: "colorCell", cellType: ColorCollectionViewCell.self)) {
            //#3. 셀 구성은 클로저에서 (itemIndex, modelData, CollectionViewCell 순서대로 전달)
            index, color, cell in
            
            cell.backgroundColor = color
            cell.hexLabel.text = color.rgbHexString
        }
        .disposed(by: bag)
        
        //#4. itemSelected 혹은 modelSelected
        listCollectionView.rx.modelSelected(UIColor.self)
            .subscribe(onNext: {color in
                print(color.rgbHexString)
            })
            .disposed(by: bag)
        
        //#5. delegate 연결
        listCollectionView.rx.setDelegate(self)
            .disposed(by: bag)
    }
}


extension RxCocoaCollectionViewViewController: UICollectionViewDelegateFlowLayout {
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        guard let flowLayout = collectionViewLayout as? UICollectionViewFlowLayout else {
            return CGSize.zero
        }
        
        let value = (collectionView.frame.width - (flowLayout.sectionInset.left + flowLayout.sectionInset.right + flowLayout.minimumInteritemSpacing)) / 2
        return CGSize(width: value, height: value)
    }
}

1. 데이터 바인딩

  • 바인딩할 옵저버블 생성
  • 컬렉션뷰에 바인딩
  • bind(to:)의 클로저에서 셀 구성

2. 델리게이트

  • itemSelected: index 필요 시 사용
  • modelSelected: 모델 자체 필요 시 사용
  • 델리게이트 연결은 setDelegate
profile
iOS 개발자가 되기 위한 스터디룸/스터디의 레퍼런스는 모두 kxcoding

0개의 댓글