微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

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

import UIKit

class GridCollectionViewCell: UICollectionViewCell {
    @IBOutlet weak var label: UILabel!
}
import UIKit

private 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
    }



}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐