【问题标题】:Add data and reload CollectionView after dismiss ImagePicker - Swift - iOS在关闭 ImagePicker 后添加数据并重新加载 CollectionView - Swift - iOS
【发布时间】:2016-10-28 07:27:40
【问题描述】:

在我的应用中,用户可以使用 imagepicker 选择图像。在他选择之后,我想用新图像更新我的收藏视图(或表格视图)。 但即使调用了重新加载函数并且新项目在我的列表中,UI 也不会刷新。

编辑突出显示:我使用取消关闭来简化代码,因为行为是相同的。 我知道我必须调用 didFinishWith... 但我想强调由解雇引起的行为。

var files = [File]() // populate my collectionview or tableview

// ... code
// ... more code 

func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {

    self.dismiss(animated: true) {

        let newFile = File(name: "test")
        self.files.append(newFile)

        DispatchQueue.main.async {
            self.collectionView?.reloadData()
            // self.tableView?.reloadData() has the same behavior 
        }
    }
}

如果我在 collectionView-CellForItemAt 中打印...我看到列表中有我的新元素,但它没有显示在屏幕上。

我尝试了不同的东西,但没有任何效果或对我来说似乎很脏。有什么想法可以正确执行吗?

(我已经看到这个话题了:UICollectionView won't reloadData() after UIImagePickerController dismisses

编辑以获取更多信息:

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {

    return self.files.count
}

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ItemCell", for: indexPath) as! CollectionViewCell

        cell.file = self.files[indexPath.row]
        cell.filenameLabel.text = self.files[indexPath.row].name
        // other customization of cell
        print(cell.file.name)
        return cell
    }

【问题讨论】:

  • 你应该使用这个方法:didFinishPickingMediaWithInfo并显示你的代码CellForItemAt
  • @Lyume 我认为对于这种类型的要求,您应该使用 PHASSET
  • 正如我所说,我只是给你看带有取消的例子,以简化理解。

标签: ios swift uitableview uicollectionview reloaddata


【解决方案1】:

您正在实施 imagePickerControllerDidCancel。如果用户选择了一个图像,选择器不会使用 imagePickerControllerDidCancel 调用委托,而是调用didFinishPickingMediaWithInfo

【讨论】:

  • 我知道,我只是简化代码,因为行为是一样的。
  • 而不是 .reloadData() 调用 collectionView.insertItems(at:) 此方法断言您的模型是否与 collectionView 不匹配,很可能是这种情况。断言应该告诉您是否缺少单元格。
【解决方案2】:

试试我的目标 c 代码:

[objCollectionView reloadData];

[objCollectionView.collectionViewLayout invalidateLayout];

 [objCollectionView performBatchUpdates:^{
                } completion:^(BOOL finished) {

                }];

【讨论】:

  • 谢谢,但没有任何改变。我仍然在控制台中有我的对象,但在 UI 中没有。
  • self.files.append(newFile) 这个有什么用? self.files 的类型是什么?
  • self.files 填充我的 collectionView 并且是 [File] 类型。文件是一个简单的对象,带有名称、图像等。我编辑了我的帖子,这样你就可以看到我在哪里使用 self.files
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-06-30
  • 1970-01-01
  • 1970-01-01
  • 2014-08-24
  • 1970-01-01
  • 2020-03-25
  • 2021-05-28
相关资源
最近更新 更多