Swift UICollectionView橫向分頁滾動(dòng),cell左右排版

廢話不多說,直接上代碼

自定義一個(gè)SYitemViewLayout,繼承UICollectionViewFlowLayout

mport UIKit

//根據(jù)需求設(shè)置列跟行
let kEmotionCellNumberOfOneRow = 3
let kEmotionCellRow = 2

class SYitemViewLayout: UICollectionViewFlowLayout {
    
    // 保存所有item
    fileprivate var attributesArr: [UICollectionViewLayoutAttributes] = []
    
    // MARK:- 重新布局
     override func prepare() {
         super.prepare()
         
         let itemWH: CGFloat = (kScreenWitdh - 30) / CGFloat(kEmotionCellNumberOfOneRow)
         
         // 設(shè)置itemSize
         itemSize = CGSize(width: itemWH, height: itemWH - 50)
         minimumLineSpacing = 0
         minimumInteritemSpacing = 0
         scrollDirection = .horizontal
         
         // 設(shè)置collectionView屬性
         collectionView?.isPagingEnabled = true
         collectionView?.showsHorizontalScrollIndicator = false
         collectionView?.showsVerticalScrollIndicator = true
//         let insertMargin = (collectionView!.bounds.height - 3 * itemWH) * 0.5
//        collectionView?.contentInset = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)
         
         var page = 0
         let itemsCount = collectionView?.numberOfItems(inSection: 0) ?? 0
         for itemIndex in 0..<itemsCount {
             let indexPath = IndexPath(item: itemIndex, section: 0)
             let attributes = UICollectionViewLayoutAttributes(forCellWith: indexPath)
             
             page = itemIndex / (kEmotionCellNumberOfOneRow * kEmotionCellRow)
             // 通過一系列計(jì)算, 得到x, y值
             let x = itemSize.width * CGFloat(itemIndex % Int(kEmotionCellNumberOfOneRow)) + (CGFloat(page) * (kScreenWitdh - 30))
             let y = itemSize.height * CGFloat((itemIndex - page * kEmotionCellRow * kEmotionCellNumberOfOneRow) / kEmotionCellNumberOfOneRow)
             
             attributes.frame = CGRect(x: x, y: y, width: itemSize.width, height: itemSize.height)
             // 把每一個(gè)新的屬性保存起來
             attributesArr.append(attributes)
         }
         
     }
     
     override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
         var rectAttributes: [UICollectionViewLayoutAttributes] = []
         _ = attributesArr.map({
             if rect.contains($0.frame) {
                 rectAttributes.append($0)
             }
         })
         return rectAttributes
     }
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容