【发布时间】: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