引入三个变量
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
网友评论