collectionView에 셀을 레지스터 해준다
collectionView.dataSource = self 를 해주고 data SourceMethod를 만들어준다
data Source method를 만들어줄때 셀에 백그라운드 컬러를 줘야한다
------ 이까지만 해도 셀과 레이아웃이 다나오기는 한다 collectionViewLayout: UIcollectionviewFlowLayout() 이어야한다 이것을 그냥 UICollectionViewLayout으로 주면 안나온다 -----
let layout = UICollectionViewFlowLayout()
layout.itemSize = CGSize(width: 30, height: 30)
collectionView.collectionViewLayout = layout
하지만 indexPath마다 셀의 크기가 달라진다면 UICollectionViewDelegateFlowLayout 프로토콜을 써서 만들어준다 다만 이때
UICollectionView.delegate = self 를 잊으면 안된다
import UIKit
class ViewController: UIViewController, UICollectionViewDelegateFlowLayout {
private lazy var collectionView: UICollectionView = {
let cv = UICollectionView(frame: .zero, collectionViewLayout: UICollectionViewFlowLayout())
cv.register(CustomCell.self, forCellWithReuseIdentifier: CustomCell.identifier)
cv.dataSource = self
return cv
}()
override func viewDidLoad() {
super.viewDidLoad()
configureUI()
}
private func configureUI() {
view.addSubview(collectionView)
collectionView.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
collectionView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor),
collectionView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
collectionView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
collectionView.bottomAnchor.constraint(equalTo: view.bottomAnchor)
])
}
}
extension ViewController: UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 100
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: CustomCell.identifier, for: indexPath)
cell.backgroundColor = .yellow
return cell
}
}