如何将核心数据中的图像放入UICollectionView中?

时间:2019-05-04 14:16:09

标签: swift core-data uicollectionview

我对Xcode比较陌生,我想将CoreData中拥有的图像显示在图像滑块(uicollectionview)中。图像滑块与我在数组中引用的某些图像配合得很好,但是我想使用核心数据中的图像。我该怎么办?

1 个答案:

答案 0 :(得分:0)

var arrAllpost = [post]()

struct post{

    var Images:[UIImage]
 }

func fetchData(){

   let context = (UIApplication.shared.delegate as! 
                             AppDelegate).persistentContainer.viewContext
   let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: 
   "PhotoData")

do {
    let results = try context.fetch(fetchRequest)
    for dict in results 
    {
         let imagestr = dict["ImagesName"] as! String
         let array = imagestr.components(separatedBy: ", ") // store image 
     in directory and save image name with comma separated in one string 
          in core data and then that string split by comma and store in 
       name array then load that imagename's image from directory

       let arrPostImages = NSMutableArray()
        for i in array
        {
           let postimage = loadImageFromDirectory(str: i)  //get image from 
                                                              directory
           arrPostImages.add(postimage)
        }
       arrAllPost.append(post(Images: arrPostImages))
     }

}catch let err as NSError {
    print(err.debugDescription)
}
}
 // tableview delegate method
   func tableView(_ tableView: UITableView, numberOfRowsInSection section: 
      Int) -> Int {
        return arrAllPost.count;
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: 
         IndexPath) -> UITableViewCell {
        let cell = tablePost.dequeueReusableCell(withIdentifier: "Cell", 
      for: indexPath)

                    let item = arrAllPost[indexPath.row] as! Post
                      for img in item.Images
                     {
                              cell.postimageView.image = img
                      }

        return cell;
    }