我试图在按下时获取 Collection View 单元格中标签的文本。我知道以常规方式执行此操作将涉及使用 [indexPath.row] 函数,但是构成 Collection View 的数组是使用 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)
}
我正在尝试将选定的 Collection View 单元格标签中的文本保存到变量“id”。这是 Collection View 的声明:
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”变量时如何保存文本?
最佳答案
您不应该像这样在 didSelectItemAt
中出列一个新的 collectionViewCell。您要查找的函数是 collectionView.cellForItem(at: indexPath)
,它返回所选的单元格。
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
guard let cell = collectionView.cellForItem(at: indexPath) as? CCCollectionViewCell else {
// couldn't get the cell for some reason
return
}
id = cell.pLabel.text![Project.name] // ?
print(id)
}
我不确定你想在这里做什么。您声明要将单元格的 label.text 保存到您的 id
变量中。为什么要尝试使用 [Project.name]
为文本下标?
关于ios - 如何使用 CoreData 从选定的 Collection View 单元格中获取标签文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42887606/