Development/RxSwift
RxSwift) RxCocoa - UICollectionView
Tunko
2022. 6. 15. 19:52
RxCocoa 를 이용해 UICollectionView를 사용
let systemColors = [UIColor.systemRed,
UIColor.systemOrange,
UIColor.systemYellow,
UIColor.systemGreen,
UIColor.systemTeal,
UIColor.systemBlue,
UIColor.systemIndigo,
UIColor.systemPurple,
UIColor.systemPink,
UIColor.systemBrown]
@available(iOS 14.0, *)
class TestViewController: UIViewController {
@IBOutlet weak var collectionView: UICollectionView!
let disposeBag = DisposeBag()
let colorObservable = Observable.of(systemColors)
override func viewDidLoad() {
super.viewDidLoad()
colorObservable.bind(to: collectionView.rx.items(cellIdentifier: "colorCell", cellType: ColorCollectionViewCell.self)) { index, color, cell in
cell.backgroundColor = color
cell.hexLabel.text = color.accessibilityName
}
.disposed(by: disposeBag)
collectionView.rx.modelSelected(UIColor.self)
.subscribe { color in
print(color.rgbHexString)
}
.disposed(by: disposeBag)
collectionView.rx.setDelegate(self)
.disposed(by: disposeBag)
}
}
@available(iOS 14.0, *)
extension TestViewController: 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)
}
}
결과 화면
반응형