[TIL] 2021.06.04

승아·2021년 6월 4일
0
post-custom-banner

RxCocoa로 CollectionView 구현하기 ( 참고 사이트 )

Delegate 사용

extension ViewController: UICollectionViewDataSource{
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return 100
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CollectionViewCell", for: indexPath) as? CollectionViewCell else {
            return UICollectionViewCell()
        }
        
        cell.label.text = "\(indexPath.item + 1)"
        
        return cell
    }
}

extension ViewController: UICollectionViewDelegate{
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        print("\(indexPath.item)")
    }
}

RxCocoa 사용

_ = Observable.just((1...100).map{"\($0)"})
    .bind(to: collectionView.rx.items(cellIdentifier: "CollectionViewCell", cellType: CollectionViewCell.self)){ (index, element, cell) in
        cell.label?.text = "\(element)"
    }

_ = collectionView.rx
           .modelSelected(String.self)
           .subscribe(onNext:  { item in
               print("\(item)")
           })
           .disposed(by: disposeBag)
post-custom-banner

0개의 댓글