Trying to refresh a collection view using alert completion

时间:2019-03-17 22:40:50

标签: ios swift uicollectionview uialertcontroller

I have a screen with a collection view, and a plus sign bar button item. When the plus sign is pressed, an alert window pops up, where the user can add information to the list. Upon hitting OK, I am trying to refresh the collection view, but I'm doing something wrong.

The print statement "passed guard" is achieved, and I can get the information they entered. Just can't refresh the view to reflect this without leaving and coming back. Any guidance? I've run into this a few times actually, so I'm clearly missing something. Thanks very much in advance.

    @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)
    }

1 个答案:

答案 0 :(得分:1)

May be you need to alter the collection dataSource

guard let textFields = alert.textFields else { return }

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