[英]How to Get Label Text from Selected Collection View Cell with CoreData?
我试图获取按下时在集合视图单元格中的标签文本。 我知道以常规方式执行此操作会涉及使用[indexPath.row]函数,但是使用收集数据创建的数组是使用CoreData的。 当我尝试使用[indexPath.row]时,它说:“'下标'不可用:不能用Int下标String,请参见文档注释以进行讨论。” 这是我的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
}
注意:项目是CoreData实体,名称是属性。
有没有人知道在单元格单击“ 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]
下标文本?
理想情况下,您不应在单元格中公开IBOutlet
。 代替…
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)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.