swift 快速奔跑的兔几 本节的内容是:集合视图

来源:互联网 发布:软件人才需求量 编辑:程序博客网 时间:2024/05/02 04:53

集合视图是一种用于显示对象集合的工具。iOS和OS X上面都有集合视图,但是iOS上的实现要更好一些。下面就要说一说iOS下的UICollectionView。
利用UICollectionView,可以采用某种方式来呈现一组项目,不需要每个项目知道它是如何确定位置或者如何布局的。UICollectionView的行为方式与UITableView非常类似,但它并不是直接采用垂直列表的形式来设定内容布局,而是支持一种可以自定义的布局处理器,名为布局对象。
UICollectionView类利用了数据源和委托。UICollectionView显示一组UICollectionViewCell对象,他们是UIView的子类,知道如何在集合视图中进行布局。通常,我们会创建这些单元格的子类,并用内容填充它们。
下面是代码的栗子,可以得到一个可以向下滚动的数字网格(记得在故事板内设置字体颜色为白色喔):

import UIKitclass GridCollectionViewCell: UICollectionViewCell {    @IBOutlet weak var label: UILabel!}
import UIKitprivate let reuseIdentifier = "Cell"class GridCollectionViewController: UICollectionViewController {    var numbers : [Int] = []    override func viewDidLoad() {        super.viewDidLoad()        for i in 1...200{            numbers.append(i)        }    }    override func didReceiveMemoryWarning() {        super.didReceiveMemoryWarning()        // Dispose of any resources that can be recreated.    }    override func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {        // #warning Incomplete implementation, return the number of sections        return 1    }    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {        // #warning Incomplete implementation, return the number of items        return self.numbers.count    }    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath)        if let gridCell = cell as? GridCollectionViewCell{            gridCell.label.text = String(self.numbers[indexPath.row])        }        return cell    }}
0 0