xrs3
xrs3

Reputation: 37

How to update UI following button press?

I have a UIAlert which is triggered by a button, where the user then enters a string, which is added to an array I have created called roomList.

How do I get the array to update on screen in my tableview when the user presses ok? currently I can only see the printed update when press the button again. Code below

func showAlert() {
    let alert = UIAlertController(title: "Enter New Room", message: "Add your new room below", preferredStyle: UIAlertController.Style.alert)
    alert.addAction(UIAlertAction(title: "Ok", style: UIAlertAction.Style.default) { _ in
        if let room = alert.textFields?.first?.text {
            roomList.append(room)
        }
    })
    alert.addTextField { (textField) in
        textField.placeholder = "Enter Room Name"
    }
    present(alert, animated: true, completion: nil)
    print(roomList)

Upvotes: 0

Views: 249

Answers (1)

Shehata Gamal
Shehata Gamal

Reputation: 100549

Reload the table here , add the print inside the if statement

if let room = alert.textFields?.first?.text {
    self.roomList.append(room)
    print(self.roomList)
    self.tableView.reloadData()
}

the print statement executes when you click the button while the callback that contains the if statement executes when you click the ok button of the alert

Upvotes: 1

Related Questions