尝试向集合视图中的标签添加文本时收到错误

Receiving an error of when trying to add text to a label in a collection view

我试图在集合视图中输入 arrayOfValues[indexPath.item] 作为我的 textLabel 的文本,但是当我 运行 程序说 'Fatal error: Index Out of Range'

我该如何解决这个问题,以便使用 arrayOfValues 中的信息填充 collectionView 单元格?

这是代码。

import UIKit

class NetworkViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate {

@IBOutlet weak var firstCollectionView: UICollectionView!
@IBOutlet weak var secondCollectionView: UICollectionView!

let arrayOfOrganizations = ["My Network", "Find Connections", "ss"]
let arrayOfValues = [""]

override func viewDidLoad() {
    super.viewDidLoad()

}

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    if (collectionView == secondCollectionView) {
        return arrayOfOrganizations.count
    }
    return arrayOfValues.count
 }

 func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let firstCell = firstCollectionView.dequeueReusableCell(withReuseIdentifier: "firstCell", for: indexPath) as! FirstCollectionViewCell
    firstCell.textLabel.text = arrayOfValues[indexPath.item] //error on this line
    if (collectionView == secondCollectionView) {
        let secondCell = secondCollectionView.dequeueReusableCell(withReuseIdentifier: "secondCell", for: indexPath) as! SecondCollectionViewCell
        secondCell.backgroundColor = .black
        return secondCell
    }
    return firstCell
 }

}

class FirstCollectionViewCell: UICollectionViewCell {

@IBOutlet weak var textLabel: UILabel!

}

class SecondCollectionViewCell: UICollectionViewCell {

}

您遇到的问题是无论 collectionView 是什么,您的 cellForItemAt 函数的前两行都会被执行。因此,本质上,您需要确保仅当 collectionView == firstCollectionView 时才执行与 firstCollectionView 对应的代码块,secondCollectionView 也是如此。简而言之,您只需要将您的功能改为:

 func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    if (collectionView == secondCollectionView) {
        let secondCell = secondCollectionView.dequeueReusableCell(withReuseIdentifier: "secondCell", for: indexPath) as! SecondCollectionViewCell
        secondCell.backgroundColor = .black
        return secondCell
    } else {
         let firstCell = firstCollectionView.dequeueReusableCell(withReuseIdentifier: "firstCell", for: indexPath) as! FirstCollectionViewCell
         firstCell.textLabel.text = arrayOfValues[indexPath.item] //error on this line
         return firstCell
    }
 }