不用xib創建時,需要重寫
override init(collectionViewLayout layout: UICollectionViewLayout){}
在調用時需傳 UICollectionViewLayout值,不然就會報錯
let layout = UICollectionViewFlowLayout.init()
let vc1 = DataCollectionViewController.init(collectionViewLayout: layout)
接下來就是cell的註冊以及調用了
self.collectionView!.register(DataCollectionViewCell.self, forCellWithReuseIdentifier: reuseIdentifier)
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of items
return self.leagueNameArr.count
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! DataCollectionViewCell
cell.titleLabel.text = self.leagueNameArr[indexPath.item]
return cell
}
如果需要設置item的大小以及距離上左下右的距離就得加上UICollectionViewDelegateFlowLayout協議,並遵循一下方法
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize.init(width: 60, height: 30)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
return UIEdgeInsets.init(top: 5, left: 10, bottom: 5, right: 10)
}
此時,"run"會發現view的背景色是黑色的.我們需要在override init(collectionViewLayout layout: UICollectionViewLayout) {}方法中加上設置背景色
self.collectionView?.backgroundColor = UIColor.init(red: 237/255, green: 237/255, blue: 237/255, alpha: 1)
ok,差不多就這麼多了