非void函数应返回一个值

时间:2019-07-26 01:00:44

标签: ios swift return uicollectionviewcell

我目前正在尝试制作日历,并且此错误不断弹出。

我尝试返回0,然后返回UICollectionViewCell

class ViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource {
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

    }

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

   private func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {return }

非无效函数应返回一个值

2 个答案:

答案 0 :(得分:1)

如果您想返回0和UICollectionViewCell, 你应该把它们退还

class ViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource {

  func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
      let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "nameOfIdentifier", for: indexPath) 
      return cell
}
  func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {return 0}

答案 1 :(得分:0)

首先,如果您使用的是UICollectionView,则可能需要显示至少1个UICollectionViewCell

为此,有UICollectionViewDataSource个方法。

0中返回collectionView(_: numberOfItemsInSection:)不会做任何有用的事情。就像我有一个collectionView一样,并且不想显示任何内容(直到并且除非有特定条件返回0为止)。

因此,该方法必须返回要在cells中显示的collectionView的数量。

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

现在出现了您要面对的错误: 非无效函数应返回一个值

该错误是由于其他UICollectionViewDataSource's方法(即collectionView(_: cellForItemAt:))引起的。此方法希望您returncollectionViewCell中可见的实际collectionView

在您添加的代码中,您仅调用return。相反,您必须像这样return UICollectionViewCell的实例,

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "YOUR_CELL_IDENTIFIER", for: indexPath)
    return cell
}
相关问题