在一些應用中我們會看到一些特殊的佈局方式比如 Pinterest 的瀑布流。
而我們只要通過自定義 UICollectionViewLayout 就可以實現。
CardLayout
可以設定畫面上最多會有幾張卡片,卡片向做滑動可以滑出畫面,向右可以將卡片滑入。
CardCell
CardCell 只有放一張圖片,在 loadContent 後載入圖片、設定基本樣式。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
class CardCell: UICollectionViewCell { @IBOutlet weak var imageView: UIImageView! var imageName:String? override func awakeFromNib() { super.awakeFromNib() // Initialization code } func loadContent() { if imageName == nil { return } if let image = UIImage(named:imageName!) { imageView.image = image } layer.cornerRadius = 20 layer.borderColor = UIColor.white.cgColor layer.borderWidth = 2 } } |
CardCollectionViewLayout
通過自定義 UICollectionViewLayout 來定義出卡片滑動的佈局效果。
基本參數
可以對 CardCollectionViewLayout 設定 itemSize / spacing / maximumVisibleItems
並且在設定的時候調用 invalidateLayout 方法,觸發畫面重新 render 機制,這裡會檢查 collectionView 是否存在。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
public var itemSize: CGSize = CGSize(width: 250, height: 400) { didSet{ if collectionView != nil { invalidateLayout() } } } public var spacing: CGFloat = 16.0 { didSet{ if collectionView != nil { invalidateLayout() } } } public var maximumVisibleItems: Int = 4 { didSet{ if collectionView != nil { invalidateLayout() } } } |
Reference
- 在 Github 上可以下載本文的 Source Code