Search code examples
swiftuialertviewuialertviewcontroller

alertview textField returning empty string


class x: UIViewController {

    let fromLocationLbl = UILabel()

    override func viewDidLoad() {
        super.viewDidLoad()

        let editTextField = UITextField()

        let alertController = UIAlertController(title: "Alert!", message: "Please enter from location", preferredStyle: .alert)
        alertController.addTextField { editTextField in
            editTextField.placeholder = "Enter correct name"
            // editTextField.text = self.fromLocationLbl.text
        }

        let confirmAction = UIAlertAction(title: "Change", style: UIAlertActionStyle.default) { (UIAlertAction) in
            print(editTextField.text) ///////printing optional("")
            self.fromLocationLbl.text = editTextField.text
        }

        alertController.addAction(confirmAction)
        let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)
        alertController.addAction(cancelAction)
        present(alertController, animated: true, completion: nil)
    }
}

Solution

  • editTextField isn't the same UITextField as you're adding to alert. In addTextField closure, editTextField is just name for parameter of closure which can be replaced with any other name

    alertController.addTextField { textField in
        textField.placeholder = "Enter correct name"
        // textField.text = self.fromLocationLbl.text
    }
    

    You need to get reference for first text field in your alertController

    let confirmAction = UIAlertAction(title: "Change", style: .default) { _ in
        self.fromLocationLbl.text = alertController.textFields?.first?.text
    }