swift 中UICollection的一些简单的用法

前端之家收集整理的这篇文章主要介绍了swift 中UICollection的一些简单的用法前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

//1 viewDidLoad 里面

overridefunc viewDidLoad() {

super.viewDidLoad()

self.view.backgroundColor =UIColor.whiteColor()

let flowLayout =UICollectionViewFlowLayout()//瀑布流

//布局collection

var collection = UICollectionView(frame:CGRectMake(0,0,self.view.frame.size.width,self.view.frame.size.height),collectionViewLayout: flowLayout)

collection.backgroundColor =UIColor.yellowColor()

//flowLayout.minimumLineSpacing = 10.0;//行间距(最小值)

//flowLayout.minimumInteritemSpacing = 50.0;//item间距(最小值)

collection.delegate =self

collection.dataSource =self

collection.registerClass(SCollectionViewCell.self,forCellWithReuseIdentifier:"cell")

//这个是关键要注册cell

self.view.addSubview(collection)

// Do any additional setup after loading the view.

}


//2 实现代理方法

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

var cell:UICollectionViewCell = collectionView.dequeueReusableCellWithReuseIdentifier("cell",forIndexPath: indexPath)

as!UICollectionViewCell

cell.backgroundColor =UIColor.redColor()

return cell

}

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

return 20 //返回cell的个数

}

func numberOfSectionsInCollectionView(collectionView:UICollectionView) -> Int{

return 1 //区间

}

//layout的布局

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

if (indexPath.row %2 != 0 && indexPath.row %3 != 0) {

return CGSizeMake(140,70);//长的

}else{

return CGSizeMake(70,0)">方的

}

}

//两个cell的间隔

func collectionView(collectionView: UICollectionView,insetForSectionAtIndex section: Int) -> UIEdgeInsets {

return UIEdgeInsetsMake(5,5,5)

}

//选中cell

func collectionView(collectionView: UICollectionView,didSelectItemAtIndexPath indexPath: NSIndexPath) {

print(indexPath.row)

}

原文链接:https://www.f2er.com/swift/326122.html

猜你在找的Swift相关文章