集合视图单元格获取数据

时间:2017-07-25 16:42:57

标签: ios core-data

我是收藏视图的新手。我想从CoreData中检索集合视图单元格的数据。我知道如何检索表视图单元格但是当我使用类似的方法来获取集合视图时它失败了。以下是我在CoreDataHelper和ViewController类

中的函数
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if let identifier = segue.identifier {
        if identifier == "displayCellDetail" {
            print("Task View cell tapped")


      CollectionViewCoreDataHelper.retrieveTasks()


    let indexPath = collectionView.indexPathsForSelectedItems!

         let task = tasks[indexPath.row]
    let TaskSettingViewController = segue.destination as! ViewController

           TaskSettingViewController.task = task

        } else if identifier == "addTask" {
            print("+ button tapped")
        }
    }
}


static func retrieveTasks() -> [Tasks] {
    let fetchRequest = NSFetchRequest<Tasks>(entityName: "Tasks")
    do {
        let results = try managedContext.fetch(fetchRequest)
        return results
    } catch let error as NSError {
        print("Could not fetch \(error)")
    }
    return []
}

2 个答案:

答案 0 :(得分:0)

用于将数据从一个viewController传递到另一个是

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if let identifier = segue.identifier {
        if identifier == "displayCellDetail" {
            print("Task View cell tapped")

  CollectionViewCoreDataHelper.retrieveTasks()
       let cell = sender as UICollectionViewCell
       let indexPath = self.collectionView!.indexPathForCell(cell)
       let task  = self.tasks[indexPath.row] as [ToDo]

       let objTaskSettingVC = segue.destination as! TaskSettingViewController // ViewController in which you want to send the data

       objTaskSettingVC.tasks = [task] //tasks is your variable which is having same type and defined in your TaskSettingViewController 

    } 
else if identifier == "addTask" {
        print("+ button tapped")
    }
  }
}

答案 1 :(得分:0)

试试这个:

 override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if let identifier = segue.identifier {
            if identifier == "displayCellDetail" {
                print("Task View cell tapped")

      CollectionViewCoreDataHelper.retrieveTasks()

      let cell = sender as? YourCellName //Cell from which this segue is being performed
      let indexPath = self.collectionView!.indexPathForCell(cell)               
      let task  = self.tasks[indexPath.item] //Downcast to type of  task

      let objTaskSettingVC = segue.destination as! TaskSettingViewController 

           objTaskSettingVC.tasks = task 

        } 
    else if identifier == "addTask" {
            print("+ button tapped")
        }
      }
    }