swift4 swift 4 ios collection view collectionview ตัวอย่าง xcode โค้ดล่าสุดตัวอย่างการทำงาน
เพิ่มสิ่งนี้ในส่วน Delegate ที่ด้านบน
UICollectionViewDelegateFlowLayout
และใช้ฟังก์ชันนี้
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let width = (self.view.frame.size.width - 20) / 3
let height = width * 1.5
return CGSize(width: width, height: height)
}
///// ตัวอย่างโค้ดที่สมบูรณ์
สร้างในมุมมองคอลเลกชันและเซลล์มุมมองคอลเลกชันในกระดานเรื่องราวให้การอ้างอิงถึงคอลเลกชันเป็น
@IBOutlet อ่อนแอ var cvContent: UICollectionView!
วางสิ่งนี้ใน View controller
import UIKit
class ViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
var arrVeg = [String]()
var arrFruits = [String]()
var arrCurrent = [String]()
@IBOutlet weak var cvContent: UICollectionView!
override func viewDidLoad() {
super.viewDidLoad()
arrVeg = ["Carrot","Potato", "Tomato","Carrot","Potato", "Tomato","Carrot","Potato", "Tomato","Carrot","Potato", "Tomato"]
arrVeg = ["Mango","Papaya","Orange","Mango","Papaya","Orange","Mango","Papaya","Orange","Mango","Papaya","Orange","Mango","Papaya","Orange","Mango","Papaya","Orange","Mango","Papaya","Orange","Mango","Papaya","Orange","Mango","Papaya","Orange","Mango","Papaya","Orange","Mango","Papaya","Orange","Mango","Papaya","Orange","Mango","Papaya","Orange","Mango","Papaya","Orange","Mango","Papaya","Orange","Mango","Papaya","Orange","Mango","Papaya","Orange","Mango","Papaya","Orange","Mango","Papaya","Orange","Mango","Papaya","Orange"]
arrCurrent = arrVeg
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let width = (self.view.frame.size.width - 20) / 3
let height = width * 1.5
return CGSize(width: width, height: height)
}
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return arrCurrent.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! ContentCollectionViewCell
cell.backgroundColor = UIColor.green
return cell
}
}