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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容