首先创建一个xib
之后会生成一个.swift和.xib文件,xib文件中是一个已经画好的View,我们要做的就是在这个View中布局cell中的控件,比如要增加一个Label和Button
并对这个xib中的view设置属性,包括identifier和custom class
然后在CustomCollectionViewCell中,将控件与变量建立关联,方法与在storyBoard中一样
import UIKit class CustomCollectionViewCell: UICollectionViewCell { @IBOutlet weak var label: UILabel! @IBOutlet weak var okBtn: UIButton! override func awakeFromNib() { super.awakeFromNib() // 在这里实现对控件的布局 } }
最后在ViewController.swift中加载这个cell,并对CollectionView的属性进行自定义
import UIKit class ViewController: UIViewController,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout { // UICollectionViewDelegateFlowLayout已经实现了UICollectionViewDelegate: public protocol UICollectionViewDelegateFlowLayout : UICollectionViewDelegate @IBOutlet weak var collectionView: UICollectionView! private let cellIdentifier = "collectionCell" override func viewDidLoad() { super.viewDidLoad() self.collectionView.dataSource = self self.collectionView.delegate = self // 从nib中注册cell,适用于通过xib创建cell的情况;如果是通过代码创建的cell,则使用registerClass方法 collectionView.registerNib(UINib(nibName: "CustomCollectionViewCell", bundle: nil), forCellWithReuseIdentifier:cellIdentifier) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // UICollectionViewDataSource func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int { return 1 } func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return 10 } func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCellWithReuseIdentifier(cellIdentifier, forIndexPath: indexPath) as! CustomCollectionViewCell cell.label.text = "success" return cell } // UICollectionViewDelegateFlowLayout func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize { return CGSize(width: 200, height: 200) } func collectionView(collectionView: UICollectionView,layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAtIndex section: Int) -> CGFloat { return 5.0 } func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAtIndex section: Int) -> CGFloat { return 1.0 } func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAtIndex section: Int) -> UIEdgeInsets { // let frame : CGRect = self.view.frame // let margin = (frame.width - 90 * 3) / 6.0 return UIEdgeInsetsMake(1, 1, 10, 1) // margin between cells } }
最终效果图:
参考资料:
How to create custom cells for UICollectionView using Swift