【问题标题】:Collection view not showing images properly收藏视图未正确显示图像
【发布时间】:2018-01-23 12:14:07
【问题描述】:

在view B 我有一个可以从图库中获取图像的图像视图。图片在coredata中存储为NSData

现在,如果我单击提交按钮并返回到view A,我有一个collectionview,我想在其中显示图像。如果我再次转到 view B 并添加另一张图片,请点击提交并返回到 view A 我应该会看到 2 张不同的图片。

但是当我返回时,我看到的是第一张图片两次,而不是 2 张不同的图片。但是当我再次运行该应用程序时,我会看到所有不同的图像 按要求... 在view A 的viewWillAppear 中,这就是我所做的……

//Fetching from Database
let fetchRequest = NSFetchRequest<NSManagedObject>(entityName: "Customers2")

do {
    customerDetails2 = try managedContext.fetch(fetchRequest as! NSFetchRequest<NSFetchRequestResult>) as! [Customers2]

    for result in customerDetails2 {

        if let imageData = result.value(forKey: "image") as? NSData {

        }
    }
    collectionview2.reloadData()
} catch let error as NSError {
    print("Could not fetch. \(error), \(error.userInfo)")
}

在视图 A 的 numberOfItemsInSection 中......

count1 = customerDetails2.count

在view A 中的cellForRowAtIndexPath…

let dfg = customerDetails2[indexPath.row]

let asd = dfg.image

if let image = UIImage(data: asd! as Data) {
    imageArray.append(image)
    cell1.customerImageView.image = imageArray[indexPath.row]
}

【问题讨论】:

  • imageArray.append(在cellForRowAtIndexPath内)闻起来很糟糕
  • 好的..那么应该有什么而不​​是那个..?
  • 但即使我已经完成了imageArray.append(image)...

标签: ios swift uicollectionview


【解决方案1】:

问题在于下面的行

 imageArray.append(image)

正如您提到的,添加第二张图片后会出现问题 因此,您可能会再次重新加载集合视图以显示图像。 上面的代码将再次执行,它将在索引 1 处附加第 0 行的图像,在索引 2 处附加第 1 行的图像,因此当您尝试显示第 1 行的图像时,它将与第 0 行相同。 如果要缓存图像,请使用字典 如下所示

//Declare a poperty
var imageDict = Dictionary<String,UIImage>()

//At cellForRow

 imageDict["\(indexpath.row)"] = image

同时检查图像是否存在于缓存中

 if let image  = imageDict["\(indexpath.row)"] as? UIImage {

   //Load Image    
 } else {

 //Initialise from data
}

【讨论】:

  • 好的@Akhil ..谢谢。但有一个担忧。我应该在imageDict 中添加什么以及如何添加它..?
  • 您可以使用 indexpath.row 作为我更新答案的关键信息
  • 谢谢@Akhil。有效!也投了赞成票... :) 另外,您能否谈谈最初导致问题的确切原因..?没完全听懂你说的..
  • 您在重新加载之前没有清除数组。因此,每当行的单元格被触发时,内容就会被附加到数组中
猜你喜欢
  • 2020-10-18
  • 2013-12-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多