Swift 實現瀑布流

引入三個變量

let wd =UIScreen.mainScreen().bounds.size.width //屏幕寬度

letcolletionCell :Int=3//幾列

varhArr : [CGFloat] = []//數組存儲不同高度

引入collectionView并重寫

classJapanViewController:UIViewController,UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout{

@IBOutletweakvarcollectionView:UICollectionView!

overridefuncviewDidLoad() {

super.viewDidLoad()

collectionView.delegate=self

collectionView.dataSource=self

}

無載入的情況下構造完后reload

overridefuncviewWillAppear(animated:Bool) {

collectionView.reloadData()

}

重點:

colletionView中Cell的構建

funccollectionView(collectionView:UICollectionView, cellForItemAtIndexPath indexPath:NSIndexPath) ->UICollectionViewCell{

letcell = collectionView.dequeueReusableCellWithReuseIdentifier("cell", forIndexPath: indexPath)as!UICollectionViewCell

設置背景為藍

cell.backgroundColor=UIColor.blueColor()


重新計算每個cell的高度并

var remainder :Int= indexPath.row%colletionCell

var currentRow :Int = indexPath.row/colletionCell

var currentHeight :CGFloat=hArr[indexPath.row]

var positonX = CGFloat( (Int(wd) /colletionCell-8) * remainder +5*(remainder+1) )

var positionY = CGFloat((currentRow+1)*5)

for i in 0..<currentRow{

varposition = remainder + i *colletionCell

positionY +=hArr[position]

}

cell.frame=CGRectMake(positonX, positionY,CGFloat(Int(wd)/colletionCell-8),currentHeight) //重新定義cell位置、寬高

returncell

}

然后寫row和section數量

funcnumberOfSectionsInCollectionView(collectionView:UICollectionView) ->Int{

//必加這句否則refresh完崩潰

collectionView.collectionViewLayout.invalidateLayout()

return1

}

funccollectionView(collectionView:UICollectionView, numberOfItemsInSection section:Int) ->Int{

return20

}

// MARK: -控制cell的大小,需要collectionviewdelagatelayout,隨機改變cell大小的高度

funccollectionView(collectionView:UICollectionView, layout collectionViewLayout:UICollectionViewLayout, sizeForItemAtIndexPath indexPath:NSIndexPath) ->CGSize{

varrheight :CGFloat=CGFloat(80+ (arc4random() %150))

hArr.append(rheight)

returnCGSizeMake(wd/CGFloat(colletionCell) -8, rheight)

}

//cell邊距

funccollectionView(collectionView:UICollectionView, layout collectionViewLayout:UICollectionViewLayout, insetForSectionAtIndex section:Int) ->UIEdgeInsets{

returnUIEdgeInsetsMake(0,0,10,1)

}

}

完成,build

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容