記得在學習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)的不竭動力。