func createCollectionView() {
let flowLayout = UICollectionViewFlowLayout()
// Now setup the flowLayout required for drawing the cells
let space = 5.0 as CGFloat
// Set view cell size
flowLayout.itemSize = CGSizeMake(50, 50)
// Set left and right margins
flowLayout.minimumInteritemSpacing = space
// Set top and bottom margins
flowLayout.minimumLineSpacing = space
// Finally create the CollectionView
let collectionView = UICollectionView(frame: CGRectMake(10, 10, 300, 400), collectionViewLayout: flowLayout)
// Then setup delegates, background color etc.
collectionView?.dataSource = self
collectionView?.delegate = self
collectionView?.registerClass(UICollectionViewCell.self, forCellWithReuseIdentifier: "cellID")
collectionView?.backgroundColor = UIColor.whiteColor()
self.view.addSubview(collectionView!)
}
然后根据需要实现 UICollectionViewDataSource方法:
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 20;
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
var cell:UICollectionViewCell=collectionView.dequeueReusableCellWithReuseIdentifier("collectionCell", forIndexPath: indexPath) as UICollectionViewCell;
cell.backgroundColor = UIColor.greenColor();
return cell;
}
func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
import UIKit
// 1. When creating this view, instanciate this class with the param "collectionViewLayout: UICollectionViewFlowLayout".
class BespokeCollectionViewController: UICollectionViewController, UICollectionViewDelegateFlowLayout {
var cellId = "AwesomeCell"
override func viewDidLoad() {
super.viewDidLoad()
// 2. Register a reusable cell:
collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: cellId)
}
// 3. Return number of items:
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 5
}
// 4. Define the reusable cell:
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath)
// You can cast type above as such: ...for: indexPath) as! BespokeCell
return cell
}
// 5. Define the size of the cell. This depends on protocol 'UICollectionViewDelegateFlowLayout' to work:
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let width = view.frame.width // In this example the width is the same as the whole view.
let height = CGFloat(200)
return CGSize(width: width, height: height)
}
}
要使用您的定制类,不要忘记 collectionViewLayout参数:
let layout = UICollectionViewFlowLayout()
let myViewController = WorkoutViewController(collectionViewLayout: layout)