我正在使用自定义collectionCell构建UICollectionView。但是我得到了错误:
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'UICollectionView must be initialized with a non-nil layout parameter'
但是从代码中我可以看到,我非常明确地创建了布局,并在初始化集合视图时将其作为参数传递。
import UIKit
private let reuseIdentifier = "Cell"
class ProfileViewController: UICollectionViewController, UICollectionViewDelegateFlowLayout {
override func viewDidLoad() {
super.viewDidLoad()
sentMngr.retrieveSent()
let flow = UICollectionViewFlowLayout()
flow.sectionInset = UIEdgeInsets(top: 20, left: 10, bottom: 10, right: 10)
flow.itemSize = CGSize(width: 90, height: 90)
flow.scrollDirection = UICollectionViewScrollDirection.Vertical
self.collectionView = UICollectionView(frame: self.view.frame, collectionViewLayout: flow)
self.collectionView!.dataSource = self
self.collectionView!.delegate = self
self.collectionView!.backgroundColor = UIColor.blackColor()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Register cell classes
self.collectionView!.registerClass(CollectionCell.self, forCellWithReuseIdentifier: reuseIdentifier)
self.view.addSubview(self.collectionView!)
// Do any additional setup after loading the view.
}
自定义单元格代码:
import UIKit
class CollectionCell: UICollectionViewCell {
var imageView: UIImageView!
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func drawRect(rect: CGRect) {
// Drawing code
}
*/
override init(frame: CGRect) {
super.init(frame: frame)
imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: frame.size.width, height: frame.size.height*2/3))
imageView.contentMode = UIViewContentMode.ScaleAspectFit
self.addSubview(imageView)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
答案 0 :(得分:0)
尝试将代码替换为:
import UIKit
private let reuseIdentifier = "Cell"
class ProfileViewController: UICollectionViewController, UICollectionViewDelegateFlowLayout {
override func viewDidLoad() {
super.viewDidLoad()
sentMngr.retrieveSent()
self.collectionView!.backgroundColor = UIColor.blackColor()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Register cell classes
self.collectionView!.registerClass(CollectionCell.self, forCellWithReuseIdentifier: reuseIdentifier)
self.view.addSubview(self.collectionView!)
// Do any additional setup after loading the view.
}
答案 1 :(得分:0)
Swift 3.0
我遇到同样的问题,应用程序一启动就崩溃了。初始化时工作正常如下
var alarmCollectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: UICollectionViewFlowLayout.init())
我正在使用autoLayout,所以在框架中使用了CGRect.zero