Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> iOS

Tạo CollectionView Layout trong ứng dụng iOS

CollectionView hỗ trợ scroll ngang/dọc, hiển thị lưới (grid). Các bước cơ bản:

  1. Kéo UICollectionView vào Storyboard.
  2. Set reuse identifier cho cell = "cell".
  3. Tạo subclass UICollectionViewCell (ví dụ CollectionViewCell), gán class cho cell trong Storyboard.
  4. @IBOutlet collectionView, set delegate, dataSource.
  5. ViewController conform UICollectionViewDelegate, UICollectionViewDataSource.
  6. Implement numberOfItemsInSection, cellForItemAt.
  7. Để 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
}