首页 > 解决方案 > 尝试将文本添加到集合视图中的标签时收到错误消息

问题描述

我试图在集合视图中输入 arrayOfValues[indexPath.item] 作为我的 textLabel 的文本,但是当我运行程序说“致命错误:索引超出范围”时收到错误

我将如何解决这个问题,以便在 collectionView 单元格中填充来自 arrayOfValues 的信息?

这是代码。

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 {

}

标签: swiftuicollectionviewuicollectionviewcell

解决方案


您遇到的问题是无论collectionView如何,您的cellForItemAt函数的前两行都会被执行。因此,本质上,您需要确保与 firstCollectionView 对应的代码块仅在 collectionView == 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
    }
 }

推荐阅读