实例化后UICollectionVIew NIL

问题描述 投票:1回答:2

我有一个UICollectionView,作为插座连接到故事板中的UICollectionView。我将此作为我的代码的一部分:

override func viewDidLoad()
{
    super.viewDidLoad()
    SetActivityIndicator()

    let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
    layout.itemSize = CGSize(width: 80, height: 80)

    ProductsCollection = UICollectionView(frame: self.view.frame, collectionViewLayout: layout)

    ProductsCollection.dataSource = self // Here it says ProductsCollection is nil!
    ProductsCollection.delegate = self

在实例化之后,ProductsCollection = UICollectionView(frame: self.view.frame, collectionViewLayout: layout) ProductsCollection为零。我究竟做错了什么 ?

编辑:我断开了插座,但我仍然在同一行中获得零。

例外:

The Exception

swift xcode uicollectionview
2个回答
2
投票

如果您没有在故事板中创建集合视图,则需要从代码中的属性声明中删除weak

此外,变量名称以小写字母开头。它应该是productsCollectionView。确保你也更新。


2
投票

我在我的项目中编写了这段代码,一切都很完美。

import UIKit

class ViewController: UIViewController {

    var productsCollection: UICollectionView?

    override func viewDidLoad() {
        super.viewDidLoad()

        let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
        layout.itemSize = CGSize(width: 80, height: 80)

        productsCollection = UICollectionView(frame: self.view.frame, collectionViewLayout: layout)

        productsCollection?.dataSource = self
        productsCollection?.delegate = self
    }

}

extension ViewController: UICollectionViewDelegate {

}

extension ViewController: UICollectionViewDataSource {

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

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

}
© www.soinside.com 2019 - 2024. All rights reserved.