这个常用的控件有几种常用的方式,这里备注一下:
通过 Storyboard 构建
默认的方式,简单好用,可以认为是一种较为常用的方式。
- 拖拽 UICollectionViewController 控件到 Storyboard 中
- 关联控制器的 Class,关联 Cell 的 Class(自定义 Cell 时),设置重用标识(Identifier)
- 在控制器中实现相关的 Datasource 和 Deletegate 方法
Xlib 的使用
这种方式单独分离出一个UI视图文件来设计界面,通常我们可以对 CollectionView 中的 Cell 进行自定设计。
以iOS开发来说,
- 通过 iOS -> User Interface -> View 新建一个 Xlib 文件。
- 定义自己的 Cell Class
- 在控制器中将 Cell 注册到 CollectionView
self.collectionView?.registerNib(UINib(nibName: "CustomCell", bundle: nil), forCellWithReuseIdentifier: "CustomCell")
- 自定义 Xlib 的 UI 视图以满足需求
纯代码实现
这种方式最原始,相比可见的视图界面来定义UI不够直观,但它也有的方便的地方。
继承相关的类,就像这样
class TestViewController: UIViewController, UICollectionViewDelegateFlowLayout, UICollectionViewDataSource {
这里 UICollectionViewDelegateFlowLayout
也继承自 UIScrollViewDelegate
在控制器的 viewDidLoad
方法中初始化代码
override func viewDidLoad() {
super.viewDidLoad()
let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
layout.sectionInset = UIEdgeInsets(top: 20, left: 10, bottom: 10, right: 10)
layout.itemSize = CGSize(width: 90, height: 120)
collectionView = UICollectionView(frame: self.view.frame, collectionViewLayout: layout)
collectionView.dataSource = self
collectionView.delegate = self
collectionView.registerClass(UICollectionViewCell.classForCoder(), forCellWithReuseIdentifier: "Cell")
collectionView.backgroundColor = UIColor.whiteColor()
self.view.addSubview(collectionView)
}
实现相关的的接口方法
// MARK: UICollectionViewDataSource
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 14
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("CustomCell", forIndexPath: indexPath)
cell.backgroundColor = UIColor.orangeColor()
return cell
}
总结
每种方法的使用需求不一样,有时你需要方便的设计,有时你需要动态的添加控件,按照自己的需要来。