這次練習一個會縮放卡片大小的佈局效果。
FlatCardLayout
卡片在畫面兩側是呈現最小的狀態,當靠近中間的時候會放大,離開中間的時候會縮小。
FlatCardCollectionViewLayout
設定 UICollectionView 為水平移動,並且設定左右間距。
1 2 3 4 5 6 7 8 9 |
override open func prepare() { super.prepare() scrollDirection = .horizontal let inset = (collectionView!.frame.size.width - itemSize.width) * 0.5 sectionInset = UIEdgeInsets(top: 0, left: inset, bottom: 0, right: inset) } |
根據卡片的數量,設定 contentSize
1 2 3 4 5 6 7 |
override open var collectionViewContentSize: CGSize { if collectionView == nil { return CGSize.zero } let itemsCount = CGFloat(collectionView!.numberOfItems(inSection: 0)) return CGSize(width: collectionView!.bounds.width * itemsCount, height: collectionView!.bounds.height) } |
具體的佈局邏輯
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
override open func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? { if collectionView == nil { return nil } // 從supser 獲取已經計算好的佈局屬性 let attributes = super.layoutAttributesForElements(in: rect) let centerX = collectionView!.contentOffset.x + collectionView!.bounds.width / 2.0 for attribute in attributes! { // cell 中心點 和 collectionView 中心點的間距 let delta = Swift.abs(attribute.center.x - centerX) // 根據間隔距離計算縮放比例 let scale = 1.3 - delta / collectionView!.frame.size.width // 設置縮放比例 attribute.transform = CGAffineTransform(scaleX: scale, y: scale); } return attributes } |
Reference
- 在 Github 上可以看到本文相關的 Source Code
請問collectionViewContentSize.width = collectionView!.bounds.width * itemsCount ,這樣水平可以滾動的長度會是10個CollectionView的寬,不知道這樣理解有沒有錯誤還是有其他用途?
如果用預設或下面這寫法會不會比較好?
let width = (2 * inset) + (itemSize.width * 10) + self.minimumInteritemSpacing * (itemsCount – 1)
retrun CGSize(width: width, height: collectionview!.bounds.height)
沒錯,其實這一系列都可以再做得更好,但因為我把自己時間定在每天要做一個例子,所以會以實現效果為主。