【问题标题】:how to display coreData on a collection view cell (swift4)如何在集合视图单元格上显示核心数据(swift 4)
【发布时间】:2018-07-08 22:12:45
【问题描述】:

如果下面的代码显示在标签上,它会起作用。但是在这个函数中,我收到错误消息 Missing return in a function expected to return 'UICollectionViewCell'。将返回单元格放在 for 循环中不起作用。

       import UIKit

class collectionVIEW: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate {

        var users = [User]()
    @IBOutlet var theIssues: UICollectionView!
    override func viewDidLoad() {
        super.viewDidLoad()

//        users = cdHandler.fetchObject()!

    }


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

        return users.count

    }

    func getDefaultCell() -> UICollectionViewCell{
                    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! whyCollectionViewCell
    }
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {


        if cdHandler.fetchObject() != nil {
            users = cdHandler.fetchObject()!

            for c in users {

                let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! whyCollectionViewCell
                cell.general.text = "\((cell.general.text)!)+\((c.userName)!)"

                return cell
            }

        } else {
            return getDefaultCell()
        }



    }




}

【问题讨论】:

  • 关于截图:请阅读错误信息并比较dequeue... 两行。提示:区分大小写很重要。 cellForItem 中的重复循环仍然没有意义。
  • @vadian 我尝试更改 dequeue 但没有效果我用我的所有代码更新了问题。
  • 请学习了解表格视图的工作原理。 cellForItemAt为每一行分别调用多次users 数组必须填充到 cellForItemAt 之外。提取和重复循环是无意义的。

标签: ios core-data uicollectionview swift4


【解决方案1】:

cellForItemAt 方法期望在所有情况下都返回 UICollectionViewCell。在else 条件下,返回一个默认单元格,如下所示:-

  func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    if cdHandler.fetchObject() != nil {
        users = cdHandler.fetchObject()!

        for c in users {

       let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! whyCollectionViewCell
            cell.general.text = "\((cell.general.text)!)+\((c.userName)!)"

        return cell
                }

        }else{
           return getDefaultCell()
}

注意:-使用标识符defaultCcell注册集合视图

func getDefaultCell() -> UICollectionViewCell{
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "defaultCcell", for: indexPath) as! UICollectionViewCell
return cell 
}

【讨论】:

  • getDefualtcell 函数不工作 我在上面添加了一张照片让您查看错误。谢谢。
  • 将 collectionVIEW 替换为您的收藏视图的名称。
  • 那仍然收到错误消息。更新了上面的照片。谢谢。
  • 将索引路径作为参数传递给该函数并使用它。
  • 我不知道该怎么做。如果有帮助,我会用我的所有代码更新我的问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-07-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多