CollectionView hỗ trợ scroll ngang/dọc, hiển thị lưới (grid). Các bước cơ bản:
- Kéo
UICollectionViewvào Storyboard. - Set reuse identifier cho cell = "cell".
- Tạo subclass
UICollectionViewCell(ví dụCollectionViewCell), gán class cho cell trong Storyboard. @IBOutletcollectionView, setdelegate,dataSource.- ViewController conform
UICollectionViewDelegate,UICollectionViewDataSource. - Implement
numberOfItemsInSection,cellForItemAt. - Để scroll ngang: trong Storyboard chọn CollectionView → Scroll Direction = Horizontal.
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return 500 }
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! CollectionViewCell
cell.backgroundColor = .gray
return cell
}