昨天用 UICollectionView 做一個圖片顯示,但是間距怎樣看都覺得奇怪,原來是 Cell 的高度設定有問題
//set up the size of each cell
layout.itemSize = CGSize(width:CGFloat(fullScreenSize.width)/3 - 10.0, height:CGFloat(fullScreenSize.height)/3 - 110.0)
把 Cell 高度修改一下看起來舒服多了!!
試試看新增 Header 和 Footer
在 < ViewDidLoad > 中
layout.headerReferenceSize = CGSize(width:fullScreenSize.width, height:40)
layout.footerReferenceSize = CGSize(width:fullScreenSize.width, height:40)
myCollectionView.register(UICollectionReusableView.self, forSupplementaryViewOfKind:UICollectionElementKindSectionHeader, withReuseIdentifier: "Header")
myCollectionView.register(UICollectionReusableView.self, forSupplementaryViewOfKind:UICollectionElementKindSectionFooter, withReuseIdentifier: "Footer")
//contents of Header and Footer
func collectionView(_ collectionView: UICollectionView,viewForSupplementaryElementOfKind kind: String,
at indexPath: IndexPath) -> UICollectionReusableView {
// 實體化 UICollectionReusableView
var reusableView = UICollectionReusableView()
// 在 header 和 footer 建立 label 顯示文字
let label = UILabel(frame: CGRect(
x: 0, y: 0, width: fullScreenSize.width, height: 40))
label.textAlignment = .center
// header
if kind == UICollectionElementKindSectionHeader {
reusableView = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionElementKindSectionHeader,
withReuseIdentifier: "Header", for: indexPath)
//設置 header 的內容
reusableView.backgroundColor = UIColor.cyan
label.text = "Header";
label.textColor = UIColor.white
} else if kind == UICollectionElementKindSectionFooter {
reusableView = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionElementKindSectionFooter,withReuseIdentifier: "Footer", for: indexPath)
// 設置 footer 的內容
reusableView.backgroundColor = UIColor.darkGray
label.text = "Footer";
label.textColor = UIColor.black
}
reusableView.addSubview(label)
return reusableView
}