先在sotryboard內建立一個collectionviewcontroller
然後再建立一個繼承於UICollectionViewController的class
而此class會幫你建立好cell,但我個人將它移除後自己寫過,也可用系統建立的。
其餘不多說拉!以下看code
import UIKit
class MenuViewController: UICollectionViewController,UICollectionViewDelegateFlowLayout {
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 20
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! MenuViewCell;
cell.layer.cornerRadius = 10//給cell圓角
cell.nameLabel.text = "這是第\(indexPath.row)個cell"
// Configure the cell
return cell
}
override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let row = indexPath.row
print(row)
}
//MARK: CELL內容
//計算cell上下高
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize{
let size:CGSize = CGSize(width: self.view.frame.size.width/2-12, height: (self.view.frame.size.width/2-12)/1.5);
return size
}
//計算cell上下高
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat{
return 10
}
//計算cell左右寬度
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat
{
return 5
}
//cell上下左右留邊
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets{
return UIEdgeInsetsMake(10, 6, 10, 6);
}
呈現出來的效果如下
沒有留言:
張貼留言