skip to Main Content

I want to call table.reloadData() when I dismiss my UIAlertController. But I don’t know how to do it.

I tried putting table.reloadData() in ViewController’s viewWillAppear but it doesn’t work because Alert’s modalPresentationStyle cannot be changed.

I’m presenting alertController like so:

`let alert = UIAlertController(title: "Some Title", message: "Enter a text", preferredStyle: .alert)

alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { [weak alert] (_) in
 let enteredTitle = alert!.textFields![0]
 let enteredNoteDescription = alert!.textFields![1]
 
 //Save to DB
 let note = Note(context: CoreDataService.managedObjectContext)
 note.title = enteredTitle.text
 note.noteDescription = enteredNoteDescription.text
 CoreDataService.saveContext()
 }))

present(alert, animated: true, completion: nil)`

2

Answers


  1.  func showErrorAlertWithAction( withTitle: String,
                                   andMessage: String,
                                   buttonName: String,
                                   completion: @escaping (() -> Void))
    {
        let alert = UIAlertController(title: withTitle, message: andMessage, preferredStyle: .alert)
        let action = UIAlertAction(title: buttonName, style: .default) { _ in completion() }
        alert.addAction(action)
        DispatchQueue.main.async {
            self.present(alert, animated: true)
        }
    }
    

    Usage is:

        showErrorAlertWithAction(withTitle: "Some Title", andMessage: "Enter a text", buttonName: "OK") {
            // here you use action that will take effect after user taps "OK" button e.g:
            //Save to DB
            let note = Note(context: CoreDataService.managedObjectContext)
            note.title = enteredTitle.text
            note.noteDescription = enteredNoteDescription.text
            CoreDataService.saveContext()
        }
    
    Login or Signup to reply.
  2. I’ve tried this solution and worked with me:

    Suppose that your data source is:

    var elements = ["first", "second", "third"]
    

    and then your alert creation be like this:

    let alert = UIAlertController(title: "Some Title", message: "Enter a text", preferredStyle: .alert)
    alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { [weak self] _ in
         self?.elements.append("forth")
         self?.tableView.reloadData()
    }))
    present(alert, animated: true, completion: nil)
    

    So As you see I’ve reloaded the table view in the action handler completion using self?.tableView.reloadData() and the worked fine with me.
    let me know if it didn’t work with you

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search