【发布时间】:2017-12-20 08:47:09
【问题描述】:
我创建了一个继承自 UICollectionView 的类 GalleryCollectionViewController,如下所示:
import UIKit
class GalleryCollectionViewController: UICollectionViewController {
var dataSourceArr:Array<UIImage>!
override convenience init(collectionViewLayout layout: UICollectionViewLayout) {
self.init()
collectionView?.collectionViewLayout = layout
collectionView!.register(GalleryCollectionViewCell.self, forCellWithReuseIdentifier: "cell")
}
override func viewDidLoad() {
super.viewDidLoad()
}
// MARK: UICollectionViewDataSource
override func numberOfSections(in 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
if dataSourceArr.count != 0 {
return dataSourceArr.count
}
return 0
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! GalleryCollectionViewCell
cell.imageView.image = dataSourceArr[indexPath.row]
return cell
}
GalleryCollectionViewCell 已定义。
在根控制器中设置这个 viewDidLoad :
let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
layout.sectionInset = UIEdgeInsets(top: 20, left: 10, bottom: 10, right: 10)
layout.itemSize = CGSize(width: 90, height: 120)
let galleryColVC = GalleryCollectionViewController(collectionViewLayout: layout)
galleryColVC.dataSourceArr = photoLibraryImagesArr
self.present(galleryColVC, animated: true, completion: nil)
但在 UICollectionView 中出现此错误:
*** 由于未捕获的异常“NSInvalidArgumentException”而终止应用程序,原因:“UICollectionView 必须是 用非零布局参数初始化'
请帮忙解决这个问题。
【问题讨论】:
-
这似乎解释了您得到崩溃的原因:stackoverflow.com/questions/24288927/… 您需要使用初始化程序进行实例化: init(frame: CGRect, collectionViewLayout: UICollectionViewLayout) 并且您只需在 GalleryCollectionViewController 中使用 self.init()类
标签: ios swift layout swift3 uicollectionview