alertview textField返回空字符串

时间:2019-02-07 08:48:29

标签: swift uialertview uialertviewcontroller

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

1 个答案:

答案 0 :(得分:0)

editTextField与您要添加到警报中的UITextField不同。在addTextField闭包中,editTextField只是闭包参数的名称,可以用任何其他名称替换

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

您需要获取alertController

中第一个文本字段的参考
let confirmAction = UIAlertAction(title: "Change", style: .default) { _ in
    self.fromLocationLbl.text = alertController.textFields?.first?.text
}