UICollectionView 的几种自定义设计方式

2015-11-20  本文已影响554人  chansey

这个常用的控件有几种常用的方式,这里备注一下:

通过 Storyboard 构建

默认的方式,简单好用,可以认为是一种较为常用的方式。

Xlib 的使用

这种方式单独分离出一个UI视图文件来设计界面,通常我们可以对 CollectionView 中的 Cell 进行自定设计。

以iOS开发来说,

self.collectionView?.registerNib(UINib(nibName: "CustomCell", bundle: nil), forCellWithReuseIdentifier: "CustomCell")

纯代码实现

这种方式最原始,相比可见的视图界面来定义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
}

总结

每种方法的使用需求不一样,有时你需要方便的设计,有时你需要动态的添加控件,按照自己的需要来。

上一篇 下一篇

猜你喜欢

热点阅读