引入三個(gè)變量
let wd =UIScreen.mainScreen().bounds.size.width //屏幕寬度
letcolletionCell :Int=3//幾列
varhArr : [CGFloat] = []//數(shù)組存儲(chǔ)不同高度
引入collectionView并重寫
classJapanViewController:UIViewController,UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout{
@IBOutletweakvarcollectionView:UICollectionView!
overridefuncviewDidLoad() {
super.viewDidLoad()
collectionView.delegate=self
collectionView.dataSource=self
}
無載入的情況下構(gòu)造完后reload
overridefuncviewWillAppear(animated:Bool) {
collectionView.reloadData()
}
重點(diǎn):
colletionView中Cell的構(gòu)建
funccollectionView(collectionView:UICollectionView, cellForItemAtIndexPath indexPath:NSIndexPath) ->UICollectionViewCell{
letcell = collectionView.dequeueReusableCellWithReuseIdentifier("cell", forIndexPath: indexPath)as!UICollectionViewCell
設(shè)置背景為藍(lán)
cell.backgroundColor=UIColor.blueColor()
重新計(jì)算每個(gè)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數(shù)量
funcnumberOfSectionsInCollectionView(collectionView:UICollectionView) ->Int{
//必加這句否則refresh完崩潰
collectionView.collectionViewLayout.invalidateLayout()
return1
}
funccollectionView(collectionView:UICollectionView, numberOfItemsInSection section:Int) ->Int{
return20
}
// MARK: -控制cell的大小,需要collectionviewdelagatelayout,隨機(jī)改變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