iT邦幫忙

2018 iT 邦幫忙鐵人賽
DAY 15
0
Software Development

iOS Swift x Layout x Animation x Transition系列 第 15

Flat Card Layout

https://ithelp.ithome.com.tw/upload/images/20180103/20107329gDwVjCQf2Q.png

卡片在畫面兩側是呈現最小的狀態,當靠近中間的時候會放大,離開中間的時候會縮小。

Flat Card Layout

Flat Card Layout

FlatCardCollectionViewLayout

設定 UICollectionView 為水平移動,並且設定左右間距。

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

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)
}

具體的佈局邏輯

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


上一篇
CardLayout - 卡片佈局 (Custom UICollectionViewLayout)
下一篇
Hotel Card Layout
系列文
iOS Swift x Layout x Animation x Transition30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言