【问题标题】:Receiving an error of when trying to add text to a label in a collection view尝试将文本添加到集合视图中的标签时收到错误消息
【发布时间】:2020-06-08 16:39:08
【问题描述】:

我试图在集合视图中输入 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 {

}

【问题讨论】:

  • 如果你真的同时需要两个collectionviews,我建议你将它们的委托和数据源实现为两个独立的类,这样就不会发生这些混淆。

标签: swift uicollectionview uicollectionviewcell


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2021-06-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多