我试图在按下时获取集合视图单元格中的标签文本。我知道以常规方式执行此操作将涉及使用 [indexPath.row] 函数,但是创建集合视图的数组是使用 CoreData。当我尝试使用 [indexPath.row] 时,它说:“‘下标’不可用:不能用 Int 下标字符串,请参阅文档注释进行讨论。” 这就是我的 didSelect 函数目前的样子:
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cellP", for: indexPath) as! CCCollectionViewCell
id = cell.pLabel.text![Project.name]
print(id)
}
我正在尝试将所选的集合视图单元格标签中的文本保存到变量“id”中。这是集合视图的声明:
var projectList : [Project] = []
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cellP", for: indexPath) as! CCCollectionViewCell
let project = projectList[indexPath.row]
cell.pLabel?.text = project.name!
//cell.tag = indexPath.row
return cell
}
注意:Project 是一个 CoreData 实体,name 是属性。
有谁知道当单元格被点击到“id”变量时如何保存文本?
理想情况下,您不应该IBOutlet
在单元格中暴露s。反而…
class CCCollectionViewCell: UICollectionViewCell {
IBOutlet weak var pLabel: UILabel!
var project: Project? {
didSet {
pLabel.text = project?.name
}
}
}
然后在你的视图控制器中......
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cellP", for: indexPath) as! CCCollectionViewCell
cell.project = projectList[indexPath.row]
return cell
}
和…
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
cell = collectionView.cellForRow(atIndexPath: indexPath) as! CCCollectionViewCell
let project = cell.project
print(project)
}
或者…
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let project = projectList[indexPath.row]
print(project)
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句