How to add textField in UIAlertController?

前端 未结 3 1969
梦谈多话
梦谈多话 2020-12-04 18:59

I want to realize a function about changing password. It requires users to input their previous password in an alert dialog.

I want to click the button \"Confirm the

3条回答
  •  盖世英雄少女心
    2020-12-04 19:56

    Here is an updated answer for Swift 4.0 that creates the desired kind of textfield:

    // Create a standard UIAlertController
    let alertController = UIAlertController(title: "Password Entry", message: "", preferredStyle: .alert)
    
    // Add a textField to your controller, with a placeholder value & secure entry enabled
    alertController.addTextField { textField in
        textField.placeholder = "Enter password"
        textField.isSecureTextEntry = true
        textField.textAlignment = .center
    }
    
    // A cancel action
    let cancelAction = UIAlertAction(title: "Cancel", style: .cancel) { _ in
        print("Canelled")
    }
    
    // This action handles your confirmation action
    let confirmAction = UIAlertAction(title: "OK", style: .default) { _ in
        print("Current password value: \(alertController.textFields?.first?.text ?? "None")")
    }
    
    // Add the actions, the order here does not matter
    alertController.addAction(cancelAction)
    alertController.addAction(confirmAction)
    
    // Present to user
    present(alertController, animated: true, completion: nil)
    

    And how it looks when first presented:

    And while accepting text:

提交回复
热议问题