ios - 如何使用 CoreData 从选定的 Collection View 单元格中获取标签文本?

标签 ios swift core-data uicollectionview

我试图在按下时获取 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/

相关文章:

Swift Playgrounds Apple 人人能编程应用程序练习

ios - 合并并编辑2个UIImage

ios - 如何使用 Sync 将 JSON 解析为与其自身有关系的实体?

iphone - Phonegap 应用程序 : External URL don't open in InApp Browser of IOS

ios - 如何删除/解码 URL 百分比编码?

ios - 在 Swift 3 iOS 中进行 HTTP POST 时出现未知错误

ios - 如何在 iOS 中制作带有底部箭头的提示气球?

ios - Swift:使用变量来描述 UIViews

ios - 核心数据排序关系 + NSFetchedResultsController

swift - 删除相互依赖的对象时了解核心数据