带输入的 Swift 4 警报

Rya*_*ker 2 ios swift uialertcontroller

我正在尝试创建一个带有两个输入字段的警报,其中包含此应用程序的主密码。这是我的第一个应用程序。我在网上看到一个函数,想看看它是否仍然有效,但调用该函数时似乎没有弹出警报。Swift 4 中对此进行了更改吗?

func showInputDialog() {
    //Creating UIAlertController and
    //Setting title and message for the alert dialog
    let alertController = UIAlertController(title: "Choose Master Password", message: "Enter your Master and confirm it!", preferredStyle: .alert)

    //the confirm action taking the inputs
    let confirmAction = UIAlertAction(title: "Enter", style: .default) { (_) in

        //getting the input values from user
        let master = alertController.textFields?[0].text
        let confirm = alertController.textFields?[1].text

        if master == confirm {
            self.labelCorrect.isHidden = true
            self.labelCorrect.text = master
        }

    }

    //the cancel action doing nothing
    let cancelAction = UIAlertAction(title: "Cancel", style: .cancel) { (_) in }

    //adding textfields to our dialog box
    alertController.addTextField { (textField) in
        textField.placeholder = "Enter Master"
    }
    alertController.addTextField { (textField) in
        textField.placeholder = "Confirm Password"
    }

    //adding the action to dialogbox
    alertController.addAction(confirmAction)
    alertController.addAction(cancelAction)

    //finally presenting the dialog box
    self.present(alertController, animated: true, completion: nil)
}
Run Code Online (Sandbox Code Playgroud)

小智 5

    //1. Create the alert controller.
    let alert = UIAlertController(title: "Title", message: "Description", preferredStyle: .alert)


    //2. Add the text field. You can configure it however you need.
    alert.addTextField { (textField) in
        textField.placeholder = "User"
    }

    alert.addTextField { (textFieldPass) in
        textFieldPass.placeholder = "Password"
        textFieldPass.isSecureTextEntry = true
    }

    // 3. Grab the value from the text field, and print it when the user clicks OK.
    alert.addAction(UIAlertAction(title: "Cancelar", style: .default, handler: { [weak alert] (_) in
        print("cerrar")
    }))

    alert.addAction(UIAlertAction(title: "Aceptar", style: .default, handler: { [weak alert] (_) in
        let textField = alert?.textFields![0]
        let textFieldPass = alert?.textFields![1]
        print("Text field: \(textField!.text)")
        print("Text field: \(textFieldPass!.text)")
        self.Autentificacion(usuario: textField!.text!, clave: textFieldPass!.text!)
    }))
    // 4. Present the alert.
    self.present(alert, animated: true, completion: nil)
Run Code Online (Sandbox Code Playgroud)