swift+CollectionView瀑布流

記得在學習OC的時候,看到過一個CollectionView實現(xiàn)的瀑布流的項目,從網(wǎng)絡加載圖片,用SDWebImage做緩存。效果如下:


WuWeiCollectionView.gif

耐不住寂寞,于是花了2個晚上用Swift寫了一遍。用SDWebImage做緩存,You can Installation with CocoaPods or Carthage (iOS 8+),你也可以像我一樣直接把SDWebImage源碼拷貝到項目中。項目中我是在同個工程中使用 Swift 和 Objective-C,圖片屬性保存在plist中,目錄結構如下:

B5F15132-C66B-4F7C-9AE5-8D8CE11FF502.png

最關鍵的是UICollectionViewFlowLayout的設置:

//
//  WWCollectionFlowLayout.swift
//  swift_WaterfallFlow
//
//  Created by wuwei on 16/5/12.
//  Copyright ? 2016年 wuwei. All rights reserved.
//

import UIKit
class WWCollectionFlowLayout: UICollectionViewFlowLayout {

    var columnCount:Int = 0 // 總列數(shù)
    var goodsList = [WWGood]() // 商品數(shù)據(jù)數(shù)組
    private var layoutAttributesArray = [UICollectionViewLayoutAttributes]() //所有item的屬性
    
    override func prepareLayout() {
        let contentWidth:CGFloat = (self.collectionView?.bounds.size.width)! - self.sectionInset.left - self.sectionInset.right
        let marginX = self.minimumInteritemSpacing
        let itemWidth = (contentWidth - marginX * 2.0) / CGFloat.init(self.columnCount)
        self.computeAttributesWithItemWidth(CGFloat(itemWidth))
        
    }
    
    /**
     *  根據(jù)itemWidth計算布局屬性
     */
    func computeAttributesWithItemWidth(itemWidth:CGFloat){
        // 定義一個列高數(shù)組 記錄每一列的總高度
        var columnHeight = [Int](count: self.columnCount, repeatedValue: Int(self.sectionInset.top))
        // 定義一個記錄每一列的總item個數(shù)的數(shù)組
        var columnItemCount = [Int](count: self.columnCount, repeatedValue: 0)
        var attributesArray = [UICollectionViewLayoutAttributes]()
        
        var index = 0
        for good in self.goodsList {
            
            let indexPath = NSIndexPath.init(forItem: index, inSection: 0)
            let attributes = UICollectionViewLayoutAttributes.init(forCellWithIndexPath: indexPath)
            // 找出最短列號
            let minHeight:Int = columnHeight.sort().first!
            let column = columnHeight.indexOf(minHeight)
            // 數(shù)據(jù)追加在最短列
            columnItemCount[column!] += 1
            let itemX = (itemWidth + self.minimumInteritemSpacing) * CGFloat(column!) + self.sectionInset.left
            let itemY = minHeight
            // 等比例縮放 計算item的高度
            let itemH = good.h * Int(itemWidth) / good.w
            // 設置frame
            attributes.frame = CGRectMake(itemX, CGFloat(itemY), itemWidth, CGFloat(itemH))
            
            attributesArray.append(attributes)
            // 累加列高
            columnHeight[column!] += itemH + Int(self.minimumLineSpacing)
            index += 1
        }
        
        // 找出最高列列號
        let maxHeight:Int = columnHeight.sort().last!
        let column = columnHeight.indexOf(maxHeight)
        // 根據(jù)最高列設置itemSize 使用總高度的平均值
        let itemH = (maxHeight - Int(self.minimumLineSpacing) * columnItemCount[column!]) / columnItemCount[column!]
        self.itemSize = CGSizeMake(itemWidth, CGFloat(itemH))
        // 添加頁腳屬性
        let footerIndexPath:NSIndexPath = NSIndexPath.init(forItem: 0, inSection: 0)
        let footerAttr:UICollectionViewLayoutAttributes = UICollectionViewLayoutAttributes.init(forSupplementaryViewOfKind: UICollectionElementKindSectionFooter, withIndexPath: footerIndexPath)
        footerAttr.frame = CGRectMake(0, CGFloat(maxHeight), self.collectionView!.bounds.size.width, 50)
        attributesArray.append(footerAttr)
        // 給屬性數(shù)組設置數(shù)值
        self.layoutAttributesArray = attributesArray
      
    }
    
    override func layoutAttributesForElementsInRect(rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
        
        return self.layoutAttributesArray
    }
}

模型類WWGood:

import Foundation

class WWGood: NSObject {

    var w:Int = 0
    var h:Int = 0
    var price:String?
    var img:String?
    
    //字典轉模型
    static func goodWithDict(dic:NSDictionary ) -> WWGood {
        let good =  WWGood.init()
        good.setValuesForKeysWithDictionary(dic as! [String : AnyObject])
        return good
    }
    
    // 根據(jù)索引返回商品數(shù)組
    static func goodsWithIndex(index:Int8) -> NSArray {
        let fileName = "\(index % 3 + 1).plist"
        let path = NSBundle.mainBundle().pathForResource(fileName, ofType: nil)
        let goodsAry = NSArray.init(contentsOfFile: path!)
        let goodsArray = goodsAry?.map{self.goodWithDict($0 as! NSDictionary)}
        return goodsArray!
    }
    
}

UICollectionViewController

//
//  ViewController.swift
//  swift_WaterfallFlow
//
//  Created by wuwei on 16/5/11.
//  Copyright ? 2016年 wuwei. All rights reserved.
//

import UIKit

class ViewController: UICollectionViewController {

    // 商品列表數(shù)組
    var goodsList = [WWGood]()
    // 當前的數(shù)據(jù)索引
    var index:Int8 = 0
    // 底部視圖
    var footerView:WWCollectionFooterView?
    // 是否正在加載數(shù)據(jù)標記
    var loading = false
    // 瀑布流布局
    @IBOutlet weak var flowLayout: WWCollectionFlowLayout!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.collectionView?.backgroundColor = UIColor.whiteColor()
        self.loadData()
    }
    
    func loadData() {
        let goods = WWGood.goodsWithIndex(self.index)
        self.goodsList.appendContentsOf(goods as! [WWGood])
        self.index += 1
        // 設置布局的屬性
        self.flowLayout.columnCount = 3
        self.flowLayout.goodsList = self.goodsList
        self.collectionView?.reloadData()
    }
    
//MARK:- UICollectionViewDataSource
    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return self.goodsList.count
    }

    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier("GoodCellCache", forIndexPath: indexPath) as! WWGoodCell

        cell.setGoodData(self.goodsList[indexPath.item])
        return cell;
    }
    
//MARK:-FooterView
    override func collectionView(collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionReusableView {
        if kind == UICollectionElementKindSectionFooter {
            self.footerView = collectionView.dequeueReusableSupplementaryViewOfKind(kind, withReuseIdentifier: "FooterViewCache", forIndexPath: indexPath) as? WWCollectionFooterView
        }
        return self.footerView!
    }

//MARK:-scrollView代理方法
    override func scrollViewDidScroll(scrollView: UIScrollView) {
        if self.footerView == nil || self.loading == true {
            return
        }
        
        if self.footerView!.frame.origin.y < (scrollView.contentOffset.y + scrollView.bounds.size.height) {
            NSLog("開始刷新"); 
            self.loading = true
            self.footerView?.indicator.startAnimating()
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), {
                self.footerView = nil
                self.loadData()
                self.loading = false
            })
        }
        
    }
   
    override func prefersStatusBarHidden() -> Bool {
        return true
    }
}

源碼下載地址:wu大維的Github 如果你要在真機上直接運行我的代碼,請修改bundle identifier并使用你的證書。

參考資料:
Swift中文版
Using Swift with Cocoa and Objective-C

如果你都看到這里了,請給我點個贊吧,你的喜歡是我堅持原創(chuàng)的不竭動力。

最后編輯于
?著作權歸作者所有,轉載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

  • 發(fā)現(xiàn) 關注 消息 iOS 第三方庫、插件、知名博客總結 作者大灰狼的小綿羊哥哥關注 2017.06.26 09:4...
    肇東周閱讀 15,150評論 4 61
  • 結束兩天的激情穿越,我對此次草原之行的行程已心滿意足。躺在酒店沙發(fā)上,美美地記下兩天的游記。下午四點半,結伴...
    老周老師閱讀 938評論 1 3
  • 美則公司(Method)被INC.雜志評為全美成長速度最快公司的第七名,并憑借獨具一格的設計風格蟬聯(lián)“美國工業(yè)設計...
    涼意的秋閱讀 579評論 0 2
  • 這個男人,就是我的老爸。54年生人,精氣神兒不輸年輕小伙兒。 別人家的老人,這個年紀,都過上了閑云野鶴的生活,打打...
    亭主閱讀 975評論 4 13
  • 校舍是我在中學時候邂逅的一部漫畫,當時還是自己獵奇欲望比較旺盛的年代,聽到什么黑暗虐心的標簽就熱血沸騰。所以就迫不...
    伊蒂雅閱讀 4,487評論 4 3

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