[英]how to create uicollectionview with swift programatically (without storyboard)
我正在尝试以编程方式快速创建一个 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 必须使用非零布局参数进行初始化”。 我错过了什么??
您的初始值设定项看起来正确,但是,您的成员变量是使用空初始值设定项进行初始化的,该初始值设定项将在触发 viewDidLoad 之前进行评估
var collectionview1 = UICollectionView()
您可以将其更改为隐式解包,因为您立即在 viewDidLoad 中初始化这些值
var collectionview1: UICollectionView!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.