【问题标题】:Cells of UICollectionsView in Xcode Not AppearingXcode中集合视图的单元格未出现
【发布时间】:2020-07-05 09:32:08
【问题描述】:

我正在开发一个应用程序并设置一个 UICollectionView。下面是 UICollectionView 所在视图控制器的代码:

import UIKit
import Firebase
import FirebaseFirestoreSwift
import FirebaseFirestore

class scrollCollectionViewController: UICollectionViewController{
    var tournaments = [String]()
    @IBOutlet weak var collectionview: UICollectionView!
    override func viewDidLoad() {
        fetchTourneys()
        super.viewDidLoad()
        
        // Uncomment the following line to preserve selection between presentations
        // self.clearsSelectionOnViewWillAppear = false

        // Register cell classes
        

        // Do any additional setup after loading the view.
    }
    
    func fetchTourneys() {
       let db = Firestore.firestore()
       db.collection("Tournaments").getDocuments() { (querySnapshot, err) in
               if let err = err {
                   print("Error getting documents: \(err)")
               } else {
                   for document in querySnapshot!.documents {
                       print("\(document.documentID) => \(document.data())")
                       self.tournaments.append(document.documentID)
                   }
               }
       }
    }
    /*
    // 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.
    }
    */

    // MARK: UICollectionViewDataSource

    override func numberOfSections(in collectionView: UICollectionView) -> Int {
    // #warning Incomplete implementation, return the number of sections
       return self.tournaments.count
    }


    override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    // #warning Incomplete implementation, return the number of items
       return 5
    }

    override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
       let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "tourneyIdentifier", for: indexPath) as! ScrollCollectionViewCell
       cell.tournamentTitle.text = tournaments[indexPath.row]
       print(cell.tournamentTitle.text)
    // Configure the cell

       return cell
    }

    // MARK: UICollectionViewDelegate

    /*
    // Uncomment this method to specify if the specified item should be highlighted during tracking
    override func collectionView(_ collectionView: UICollectionView, shouldHighlightItemAt indexPath: IndexPath) -> Bool {
        return true
    }
    */

    /*
    // Uncomment this method to specify if the specified item should be selected
    override func collectionView(_ collectionView: UICollectionView, shouldSelectItemAt indexPath: IndexPath) -> Bool {
        return true
    }
    */

    /*
    // Uncomment these methods to specify if an action menu should be displayed for the specified item, and react to actions performed on the item
    override func collectionView(_ collectionView: UICollectionView, shouldShowMenuForItemAt indexPath: IndexPath) -> Bool {
        return false
    }

    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?) {
    
    }
    */
}

细胞只是没有最终出现。在包含一些打印语句后,我注意到 numberOfSections 的覆盖函数或集合视图似乎都没有运行。为什么这些没有运行,以及为什么单元格没有出现,可能是什么问题?

【问题讨论】:

    标签: ios swift xcode firebase uicollectionview


    【解决方案1】:

    你需要在numberOfItemsInSection中返回self.tournaments.count

    func fetchTourneys() {
        let db = Firestore.firestore()
        db.collection("Tournaments").getDocuments() { (querySnapshot, err) in
            if let err = err {
                print("Error getting documents: \(err)")
            } else {
                for document in querySnapshot!.documents {
                    print("\(document.documentID) => \(document.data())")
                    self.tournaments.append(document.documentID)
                }
                
                    self.collectionview.reloadData()
                
            }
        }
    }
    
    
    
    override func numberOfSections(in collectionView: UICollectionView) -> Int {
        // #warning Incomplete implementation, return the number of sections
               return 1
           }
    
    
           override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of items
               return self.tournaments.count
           }
    

    【讨论】:

    • 我刚刚修复了这个问题,但单元格仍然没有出现在模拟器中
    【解决方案2】:

    请移动fetchTourneys() 在 super.viewDidLoad() 之后。此外,您需要确保正确设置单元格标识符并在您的 collectionView 中注册

    private let reuseIdentifier = "tourneyIdentifier"
    
    class scrollCollectionViewController: UICollectionViewController {
        var tournaments = [String]()
    
        @IBOutlet weak var collectionview: UICollectionView!
    
        override func viewDidLoad() {
            super.viewDidLoad()
            // Register cell classes
            self.collectionview!.register(UICollectionViewCell.self, forCellWithReuseIdentifier: reuseIdentifier)
            fetchTourneys()
        }
    

    然后,在创建单元格时,重新使用reuseIdentifier

    .dequeueReusableCell(withReuseIdentifier: reuseIdentifier
    

    此外,在您的 Firebase 函数中,确保在填充数据源后告诉 collectionView 进行更新

    if let err = err {
        print("Error getting documents: \(err)")
    } else {
        for document in querySnapshot!.documents {
            print("\(document.documentID) => \(document.data())")
            self.tournaments.append(document.documentID)
        }
        self.collectionview.reloadData()
    }
    

    你也说过

    我没有注意到 numberOfSections 或 集合视图似乎正在运行

    这表明您的 UICollectionView 不知道此代码是 viewController。确保您已在 XCode Inspector 中进行设置。一般来说,Classes 和 Structs 应该以大写字母开头,vars 是小写的

    【讨论】:

    • 感谢您的回答,我想我正在取得进展。但是,我现在收到错误消息,我的自定义单元格的插座都为零。当我删除集合视图寄存器行时,它们不再为零,但仍然不会加载到屏幕上。可能是什么错误?
    • @NikhilChandra 该行是通用的,因为它将标准 UICollectionViewCell 注册到集合视图。你有一个自定义的 UICollectionViewCell 子类,所以注册你的子类。
    【解决方案3】:

    一旦fetchTourneys 完成,您必须在collectionview 上致电reloadData。

    func fetchTourneys() {
        let db = Firestore.firestore()
        db.collection("Tournaments").getDocuments() { (querySnapshot, err) in
            if let err = err {
                print("Error getting documents: \(err)")
            } else {
                for document in querySnapshot!.documents {
                    print("\(document.documentID) => \(document.data())")
                    self.tournaments.append(document.documentID)
                }
                self.collectionview.reloadData()
            }
        }
    }
    

    【讨论】:

    • 它似乎仍然不起作用。单元格不显示
    • 我打印了单元格,现在显示它有一个值,但单元格仍然没有显示在模拟器中
    • 你不需要在主线程上调用 reload ... 因为它已经在主线程上...
    • 在 Firebase 闭包中不需要 DispatchQueue.main.async。 Firebase 闭包中的 UI 调用始终称为主线程。网络是在后台线程上完成的。
    【解决方案4】:

    你需要在viewDidLoad中设置collectionview数据源并委托给self

    将delegate = self 和dataSource = self 放入viewDidLoad

    【讨论】:

      【解决方案5】:

      每个人的答案都指出了代码中的错误,从而将其移向了正确的方向。但它仍然没有显示细胞。我打印了每个单元格,并注意到有一个参数使它们全部隐藏。我不知道是什么原因造成的。但我添加了以下代码:

          cell.isHidden = false
      

      效果很好!

      【讨论】:

        猜你喜欢
        • 2016-02-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-12-04
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多