单元格不会显示在UICollectionView上

时间:2019-07-28 19:34:33

标签: swift uicollectionview

我的应用程序中有一个UICollectionView ViewController。 我为此创建了一个自定义单元,但该单元不会显示。 这是我的VC:

class NotificationVC: UICollectionViewController{

let cellId = "notificationCell"
let layout = UICollectionViewFlowLayout()

override func viewDidLoad() {
    super.viewDidLoad()
    self.navigationController?.setNavBar()
    navigationItem.title = NSLocalizedString("notification.vc.title", comment: "Notification")
    navigationItem.rightBarButtonItem?.tintColor = UIColor.appWhite

    setupCollectionView()

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

//MARK: -- CollectionView setup
fileprivate func setupCollectionView() {
    self.collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout)
    self.collectionView.backgroundColor = UIColor.appWhite
    self.collectionView!.register(NotificationCell.self, forCellWithReuseIdentifier: cellId)
    self.collectionView.delegate = self
    self.collectionView.dataSource = self
    layout.scrollDirection = .vertical

}


// MARK: UICollectionViewDataSource

override func numberOfSections(in collectionView: UICollectionView) -> Int {
    return 0
}


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

override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! NotificationCell

    return cell
}

// MARK: UICollectionViewDelegate

override func collectionView(_ collectionView: UICollectionView, canPerformAction action: Selector, forItemAt indexPath: IndexPath, withSender sender: Any?) -> Bool {
    return false
}

override func collectionView(_ collectionView: UICollectionView, performAction action: Selector, forItemAt indexPath: IndexPath, withSender sender: Any?) {

}
}

单元格只是UICollectionViewCell,我有一个UIView,UILabel和UITextView。

这是我从标签栏转到VC的方式:

  let notificationVC = UINavigationController(rootViewController: NotificationVC(collectionViewLayout: UICollectionViewFlowLayout()))

现在我只能在VC上看到背景,但是单元格本身不会显示。

3 个答案:

答案 0 :(得分:1)

let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! NotificationCell

从您的代码看来,您似乎必须将reuseIdentifier更改为cellId

您将在numberOfSections中返回0,而不是您的情况

答案 1 :(得分:0)

我认为您创建的collectionview的宽度,高度错误。因为当您将frame设置为零时,这意味着您的collectionview的宽度和高度也等于零。它由于凝结永远不会显示。  您应该将宽度和高度设置为更大的零。那时您将看到collectionview显示

答案 2 :(得分:0)

如果您将区域设置为0,则collectionview永远不会显示View的任何区域。因此,请按照您的编码更改区域。要进行检查,现在请在此方法中将区域0更改为1。

重写func numberOfSections(在collectionView中:UICollectionView)-> Int {     返回1 }

相关问题