หากต้องการใช้มุมมองคอลเลกชันอย่างรวดเร็ว อันดับแรก เราต้องสร้างมุมมองคอลเลกชัน เราสามารถลากและวางลงในกระดานเรื่องราว หรือสร้างเป็นโปรแกรมก็ได้ หลังจากนั้น เราต้องยืนยันคลาสของเรากับ UICollectionViewDataSource และ UICollectionViewDelegate นอกจากนี้ หากเราต้องการขนาดและเลย์เอาต์ของเซลล์ที่กำหนดเอง เราต้องยืนยันกับ UICollectionViewDelegateFlowLayout
มาดูขั้นตอนที่จำเป็นในการสร้างคอลเลกชัน View โดยทางโปรแกรม
func initCollection() {
let layout = UICollectionViewFlowLayout()
layout.itemSize = CGSize(width: 50, height: 50)
let collection = UICollectionView.init(frame: self.view.frame, collectionViewLayout: layout)
collection.dataSource = self
collection.delegate = self
collection.backgroundColor = colorLiteral(red: 0.3411764801, green: 0.6235294342, blue: 0.1686274558, alpha: 1)
collection.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "cell")
self.view.addSubview(collection)
} เราจำเป็นต้องเรียกใช้ฟังก์ชันข้างต้นในวิธี ViewDidLoad() ของเรา ไม่ว่าเราจะสร้างคอลเลกชันโดยทางโปรแกรมหรือด้วยกระดานเรื่องราว เราต้องจัดสรรแหล่งข้อมูลและมอบหมายเพื่อให้ข้อมูลกับตาราง และสังเกตการกระทำตามลำดับ
ตอนนี้ เราต้องบอกคอลเลกชันว่าควรมีกี่ส่วน -
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
} หลังจากนั้นเราต้องบอกว่าจะมีกี่รายการและควรมีข้อมูลอะไรบ้างในเซลล์
func collectionView(_ collection: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 7
}
func collectionView(_ collection: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collection.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath)
cell.layer.backgroundColor = colorLiteral(red: 0.4392156899, green: 0.01176470611, blue: 0.1921568662, alpha: 1)
return cell
} เราสามารถกำหนดขนาดต่างๆ ตามความต้องการได้
func collectionView(_ collection: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let size = CGSize(width: 200, height: 50)
return size
} เมื่อเราเรียกใช้โค้ดด้านบนบนอุปกรณ์ นี่คือผลลัพธ์ที่สร้างขึ้น
