简体   繁体   English

数据不会填充 UICollectionView 滚动视图

[英]Data won't populate the UICollectionView scroll view

I am brand new to this so please go easy on me!我是全新的,所以请放轻松!

My problem is as follows:我的问题如下:

I am trying to populate a scroll view (UICollectionView) with data from firebase.我正在尝试使用来自 firebase 的数据填充滚动视图 (UICollectionView)。

I am positive that it is retrieving the data successfully as I can print the data using a for loop at the end of the firebase function.我很肯定它正在成功检索数据,因为我可以在 firebase 函数末尾使用 for 循环打印数据。

The problem is that when I try to insert the data into the scroll view it says the data is out of range!!问题是,当我尝试将数据插入滚动视图时,它说数据超出范围!!

It has been pointed out to me that a scrollview is populated with the scrollView delegate methods which I have displayed below.有人向我指出,scrollview 填充了我在下面显示的 scrollView 委托方法。

It was also pointed out to me that my data source is 'self.pages'.还有人向我指出我的数据源是“self.pages”。 How to I pass the data retrieved from firebase to the delegate methods?如何将从 firebase 检索到的数据传递给委托方法?

Fatal error: Index out of range

Here is my code:这是我的代码:

//arrays of names and descriptions which are populated in firebase() function
    var names:[String] = []
    var descriptions: [String] = []

The page class:页面类:

 let imageName: UIImage
 let headerText: String
 let bodyText: String 

Here is the viewDidLoad这是 viewDidLoad

override func viewDidLoad() {
        super.viewDidLoad()

        firebase()
        setupImages()
    }

Here is the image set up function:这是图像设置功能:

 func setupImages(){

        self.pages = [
            Page(imageName: self.image, headerText: names[0], bodyText: descriptions[0]),

            Page(imageName: self.image, headerText: names[1], bodyText: descriptions[1]),

            Page(imageName: self.image, headerText: names[2], bodyText: descriptions[2]),

            Page(imageName: self.image, headerText: names[3], bodyText: descriptions[3]),

            Page(imageName: self.image, headerText: names[4], bodyText: descriptions[4]),
        ]

        self.collectionView?.backgroundColor = .white
        self.collectionView?.register(PageCell.self, forCellWithReuseIdentifier: "cellId")
        self.collectionView?.isPagingEnabled = true
    }

I think the issue is caused by the firebase data not being retrieved quick enough.我认为这个问题是由于没有足够快地检索 firebase 数据引起的。

I say this because I have another function in a different class that seems to set it up:我这样说是因为我在不同的类中有另一个函数似乎可以设置它:

override init(frame: CGRect) {
        super.init(frame: frame)
        //setup layout sets up constraints for the layout of the page
        setupLayout()
    }

Adding the UICollectionViewDataSource method's:添加 UICollectionViewDataSource 方法的:

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

and:和:

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

        let page = pages[indexPath.item]
        cell.page = page
        return cell
    }

Firebase retrieval method: Firebase 检索方法:

func firebase()
    {
        //connection to firebase for the names and descriptions
        let db = Firestore.firestore()
        db.collection(restaurauntName).getDocuments { (snapshot, err) in

            if let err = err {
                print("Error getting documents: \(err)")
            } else {
                for document in snapshot!.documents {
                    let name = document.get("Name") as! String
                    let description = document.get("Description") as! String
                    //Add names and descriptions to the arrays
                    self.names.append(name)
                    self.descriptions.append(description)
                }
            }

            for x in self.names{
                print(x)
            }

        }
    }

Thank you for reading, any way someone can put me in the right direction would be appreciated!感谢您的阅读,任何人都可以让我朝着正确的方向前进,我们将不胜感激!

Here's the issue, and your assumption is correct;这是问题所在,您的假设是正确的; the code is not flowing in the correct order.代码没有以正确的顺序流动。

override func viewDidLoad() {
   super.viewDidLoad()

   firebase()
   setupImages()
}

Firebase is asynchronous and your app needs to be structured in a way where you only attempt to work with Firebase data within the closure following the call. Firebase 是异步的,您的应用程序需要以这样一种方式构建,即您只尝试在调用后的闭包内处理 Firebase 数据。 In your viewDidLoad function, you call firebase() to load the data but the setupImages function will actually execute before Firebase has had time to get the data from the server.在您的 viewDidLoad 函数中,您调用 firebase() 来加载数据,但 setupImages 函数实际上会在 Firebase 有时间从服务器获取数据之前执行。

Fortunately, it's a simple fix.幸运的是,这是一个简单的修复。 Here's the new functions with some updated names to make the flow more clear这是具有一些更新名称的新功能,以使流程更加清晰

override func viewDidLoad() {
   super.viewDidLoad()

   self.loadDataFromfirebase()
}

and then进而

func loadDataFromFirebase() {
   let db = Firestore.firestore()
   db.collection(restaurauntName).getDocuments { (snapshot, err) in
      if let err = err {
         print("Error getting documents: \(err)")
         return
      } else {
         for document in snapshot!.documents {
            let name = document.get("Name") as! String
            let description = document.get("Description") as! String
            self.names.append(name)
            self.descriptions.append(description)
         }
         self.setupImages() //safe to do this here as the firebase data is valid
         self.collectionView.reloadData()
      }
   }
}

the concern I have is if there 25 documents... your setupImages only accesses the first 5. Likewise, if there are 3 documents, the app will crash as that function would try to access objects at index 3, 4 and those won't exist.我担心的是,如果有 25 个文档……您的 setupImages 只访问前 5 个。同样,如果有 3 个文档,应用程序将崩溃,因为该函数将尝试访问索引 3、4 处的对象,而那些不会存在。

Looking at your code: You are using self.pages as your data source.查看您的代码:您正在使用 self.pages 作为您的数据源。 I can't see a connection to Firebase in the code that you provided here.我在您在此处提供的代码中看不到与 Firebase 的连接。

The error could as well come from how you setup the cell when you pass the page in该错误也可能来自您在传入页面时如何设置单元格

cell.page = page

To quickly debug you can comment that line out and see if the error disappears.要快速调试,您可以注释该行并查看错误是否消失。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM