小编典典

错误:必须使用非nil布局参数初始化UICollectionView

swift

我正在尝试从youtube教程创建类似Facebook
Messenger的应用程序。我有一个主页,用户单击BarButton打开聊天室。主页工作正常,直到我单击BarButton打开聊天,它会崩溃并显示以下错误消息“
UICollectionView必须使用非nil布局参数初始化”。我是iOS开发的新手,因此无法真正理解问题所在,因为我已经有了init方法。由于我有不同的看法,我是否在AppDelegate中缺少某些内容,这很令人困惑:(。非常感谢您的帮助。谢谢!

class ChatViewController: UICollectionViewController, UICollectionViewDelegateFlowLayout {

override func viewDidLoad() {
    super.viewDidLoad()

    navigationItem.title = "Chats"

    collectionView?.backgroundColor = UIColor.gray

            // Do any additional setup after loading the view.
}

override func viewWillAppear(_ animated: Bool)
{
    collectionView?.register(ChatCell.self, forCellWithReuseIdentifier: "cellID")
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return 3
}

override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cellID", for: indexPath)

    return cell
}

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {

    return CGSize(width: view.frame.width, height: 100)
}

/*
// MARK: - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    // Get the new view controller using segue.destinationViewController.
    // Pass the selected object to the new view controller.
}
*/

}

class ChatCell: UICollectionViewCell
{

override init(frame: CGRect)
{
    super.init(frame: frame)
    setupViews()
}

let profileImageView: UIImageView =
{
    let imageView = UIImageView()
    imageView.contentMode = .scaleAspectFill
    imageView.translatesAutoresizingMaskIntoConstraints = false
    return imageView
}()

func setupViews()
{
    addSubview(profileImageView)

    backgroundColor = UIColor.blue

    addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|[v0]|", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0" : profileImageView]))
    addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|[v0]|", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0" : profileImageView]))
}

required init?(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
}

}

阅读 205

收藏
2020-07-07

共1个答案

小编典典

可能当您显示ChatViewController时,您会看到类似以下内容:

让chatVC = ChatViewController()

但是根据 苹果文件:

UICollectionViewController类

在初始化控制器时,使用init(collectionViewLayout :)方法,可以指定集合视图应具有的布局。

因此,您需要:

 let chatVC = ChatViewController(collectionViewLayout: UICollectionViewFlowLayout())
2020-07-07