尝试使用警报完成刷新集合视图

Trying to refresh a collection view using alert completion

我有一个带有集合视图的屏幕和一个加号栏按钮项。当按下加号时,会弹出一个警告 window,用户可以在其中向列表中添加信息。点击确定后,我试图刷新集合视图,但我做错了。

打印语句"passed guard"实现了,可以得到他们输入的信息。只是不能刷新视图来反映这一点而不离开并返回。任何指导?实际上,我已经 运行 参与过几次,所以我显然遗漏了一些东西。非常感谢。

    @objc func newButtonPressed() {
        let alert = UIAlertController(title: "Add", message: "", preferredStyle: .alert)

        alert.addTextField { (textField) in
            textField.placeholder = "Name"
        }

        alert.addAction(UIAlertAction(title: "Ok", style: .default, handler: { (action) in
            var name = ""
            guard let textFields = alert.textFields else { return }
            guard let navController = self.parent as? UINavigationController else { return }
            guard let settingsVC = navController.topViewController as? SettingsVC else { return }

            print("passed guard") // success

            DispatchQueue.main.async {
                settingsVC.collectionView.reloadData()
                settingsVC.view.backgroundColor = .red

                // For testing purposes, explicitly using main thread and setting to red
            }
        }))
        alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
        present(alert, animated: true, completion: nil)
    }

您可能需要更改集合数据源

guard let textFields = alert.textFields else { return }

settingsVC.arr.append(textFields.first!.text!) // arr is collection dataSource
settingsVC.collectionView.reloadData()