无法重新加载 Collection 查看 Swift 4

Can't Reload Collection View Swift 4

在详细视图控制器中,用户可以将角色添加到收藏夹列表。单击收藏按钮将图像 url 添加到 CoreData。然后在 collection 视图控制器中,我 运行 下面的代码:

override func viewDidLoad() {
    super.viewDidLoad()
    let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
    let request = NSFetchRequest<NSFetchRequestResult>(entityName: "Favorite")

    request.returnsObjectsAsFaults = false

    do {
        let results = try context.fetch(request)
        if results.count > 0
        {
            for result in results as! [NSManagedObject]
            {
                if let favFig = result.value(forKey: "favFig") as? String
                {
                    favFigArray.append(favFig)
                }
                if let favFigID = result.value(forKey: "favoriteID") as? String
                {
                    favFigIDArray.append(favFigID)
                }
            }

        }
    } catch {
        print("Error Fetching")
    }
}

favFigArray 然后包含图像列表 urls。要将图像设置为我的 collection 视图单元格,我使用以下代码:

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ownedCell", for: indexPath) as! OwnedCollectionViewCell
    cell.ownedFigImage.sd_setImage(with: URL(string: favFigArray[indexPath.row]))

    return cell
}

我遇到的问题是,当用户想要返回详细信息视图控制器并将更多角色添加到收藏夹列表时,collection 视图将不会更新。我尝试在 viewWillAppear 中使用 self.ownedCollectionView.reloadData() 但这不起作用。 CoreData 正在正确更新,但 favFigArray 没有更新。

任何人都可以帮我重新加载吗?谢谢!

您可以创建如下所示的过滤结果的方法,

func filterFavFigData()
     favFigArray.removeAll()

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

     request.returnsObjectsAsFaults = false

     do {
        let results = try context.fetch(request)
        if results.count > 0
        {
            for result in results as! [NSManagedObject]
            {
                if let favFig = result.value(forKey: "favFig") as? String
                {
                    favFigArray.append(favFig)
                }
                if let favFigID = result.value(forKey: "favoriteID") as? String
                {
                    favFigIDArray.append(favFigID)
                }
            }
        }
    } catch {
        print("Error Fetching")
    }
}

然后像下面这样更新您的 viewWillAppear

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    self.filterFavFigData()
    self.ownedCollectionView.reloadData()
}