如何使用swift编程创建uicollectionview(没有storyboard)

时间:2016-10-08 00:57:11

标签: ios swift uicollectionview

我正在尝试以编程方式使用swift创建一个uicollectionview,没有任何故事板。我需要它是多个uicollectionview。 这是我的代码

class jobtypeViewController: UIViewController,UICollectionViewDelegate,UICollectionViewDataSource{
var collectionview1 = UICollectionView()
var collectionview2 = UICollectionView()

override func viewDidLoad() {
    super.viewDidLoad()

    let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
    layout.sectionInset = UIEdgeInsets(top: 20, left: 10, bottom: 10, right: 10)
    layout.itemSize = CGSize(width: 100, height: 100)

    collectionview1 = UICollectionView(frame: self.view.frame, collectionViewLayout: layout)
    self.collectionview1.delegate = self
    self.collectionview1.dataSource = self
    collectionview1.registerClass(UICollectionViewCell.self, forCellWithReuseIdentifier: "Cell")
    self.view.addSubview(collectionview1)

    collectionview2 = UICollectionView(frame: self.view.frame, collectionViewLayout: layout)
    self.collectionview2.delegate = self
    self.collectionview2.dataSource = self
    collectionview2.registerClass(UICollectionViewCell.self, forCellWithReuseIdentifier: "Cell")
    self.view.addSubview(collectionview2)

}

func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    if collectionView == self.collectionview1 {
        return 5
    }else{
        return 4
    }
}

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
    if collectionView == self.collectionview1 {
        let cellA = collectionview1.dequeueReusableCellWithReuseIdentifier("Cell",forIndexPath: indexPath) as UICollectionViewCell
        return cellA
    }

    else {
        let cellB = collectionview2.dequeueReusableCellWithReuseIdentifier("Cell", forIndexPath: indexPath) as UICollectionViewCell
        return cellB
    }
}

}

一切看起来都很好我有布局,委托和数据源,但是当我运行它时我收到此消息错误终止应用程序由于未捕获的异常' NSInvalidArgumentException',原因:' UICollectionView必须是使用非零布局参数'初始化。我错过了什么吗?

1 个答案:

答案 0 :(得分:1)

您的初始化程序看起来是正确的,但是,您的成员变量是使用空的初始化程序初始化的,在触发viewDidLoad之前将对其进行评估

 var collectionview1 = UICollectionView()

您可以将其更改为隐式解包,因为您在viewDidLoad中立即初始化这些值

var collectionview1: UICollectionView!