美文网首页
Swift CollectionView的创建

Swift CollectionView的创建

作者: 迎风起飞的猪 | 来源:发表于2016-08-15 11:39 被阅读276次

import UIKit

class ViewController: UIViewController,UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout {

var colletionView : UICollectionView?

var dataArr = NSMutableArray()

override func viewDidLoad() {

super.viewDidLoad()

// Do any additional setup after loading the view, typically from a nib.

let layout = UICollectionViewFlowLayout()

colletionView = UICollectionView(frame: CGRectMake(0, 0, UIScreen .mainScreen().bounds.width, UIScreen .mainScreen().bounds.height), collectionViewLayout: layout)

//注册一个cell

colletionView! .registerClass(UICollectionViewCell.self, forCellWithReuseIdentifier:"cell")

colletionView?.delegate = self;

colletionView?.dataSource = self;

colletionView?.backgroundColor = UIColor.whiteColor()

//设置每一个cell的宽高

layout.itemSize = CGSizeMake((UIScreen .mainScreen().bounds.width-30)/2, 250)

self.view .addSubview(colletionView!)

}

//返回多少个组

func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {

return 1

}

//返回多少个cell

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

return 10

}

//返回自定义的cell

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

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

let R = (arc4random() % 256)

let G = (arc4random() % 256)

let B = (arc4random() % 256)

cell.backgroundColor = UIColor(red: CGFloat(R)/255, green: CGFloat(G)/255, blue: CGFloat(B)/255, alpha: 1.0)

return cell

}

//返回cell 上下左右的间距

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

return UIEdgeInsetsMake(10, 10, 10, 10)

}

override func didReceiveMemoryWarning() {

super.didReceiveMemoryWarning()

// Dispose of any resources that can be recreated.

}

}

相关文章

网友评论

      本文标题:Swift CollectionView的创建

      本文链接:https://www.haomeiwen.com/subject/oxjusttx.html