swift - 尝试将文本添加到集合视图中的标签时收到错误消息
问题描述
我试图在集合视图中输入 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 {
}
解决方案
您遇到的问题是无论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
}
}
推荐阅读
- r - R 包的 Travis CI:找不到部署密钥
- css - 更改 Jekyll 主题中的字体
- delphi - 发送 TMemoryStream 作为邮件附件
- angular - ng-select 在Angular 6中以编程方式删除元素
- mysql - nodejs mysql - 如何在实际项目中实现 pooledConnection?
- mongodb - Proper way to handle CosmosDb Mongo 429 error with Polly
- pandas - Pandas,使用 numpy.where() 提取正则表达式抛出 ValueError
- python - 如何在 tkinter 列表框中插入多个值?
- spring - 如何对使用 Eureka 和 Cloud config 的 Spring 微服务应用程序进行 docker 化
- python - 如何将前导数字添加到空列表并用输入填充它