How to add TextField to UIAlertController in Swift

前端 未结 13 759
余生分开走
余生分开走 2020-12-07 20:03

I am trying to show a UIAlertController with a UITextView. When I add the line:

    //Add text field
    alertController.addTextFie         


        
13条回答
  •  孤城傲影
    2020-12-07 20:29

    In Swift 4.2 and Xcode 10.1

    Alert with two Textfields and Read TextField text data and present alert on top of all views.

    func alertWithTF(title: String, message: String) {
        //Step : 1
        let alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.alert)
    
        //Step : 2
        alert.addAction (UIAlertAction(title: "Save", style: .default) { (alertAction) in
            let textField = alert.textFields![0]
            let textField2 = alert.textFields![1]
            if textField.text != "" {
                //Read textfield data
                print(textField.text!)
                print("TF 1 : \(textField.text!)")
            } else {
                print("TF 1 is Empty...")
            }
            if textField2.text != "" {
                //Read textfield data
                print(textField2.text!)
                print("TF 2 : \(textField2.text!)")
            } else {
                print("TF 2 is Empty...")
            }
        })
    
        //Step : 3
        //For first TF
        alert.addTextField { (textField) in
            textField.placeholder = "Enter your first name"
            textField.textColor = .red
        }
        //For second TF
        alert.addTextField { (textField) in
            textField.placeholder = "Enter your last name"
            textField.textColor = .blue
        }
    
        //Cancel action
        alert.addAction(UIAlertAction(title: "Cancel", style: .default) { (alertAction) in })
       self.present(alert, animated:true, completion: nil)
    
    }
    

    If you want to present aleert on top of all views.

    Here from above code remove this last line self.present(alert, animated:true, completion: nil) and add below code.

    //Present alert on top of all views.
    let alertWindow = UIWindow(frame: UIScreen.main.bounds)
    alertWindow.rootViewController = UIViewController()
    alertWindow.windowLevel = UIWindowLevelAlert + 1
    
    alertWindow.makeKeyAndVisible()
    
    alertWindow.rootViewController?.present(alert, animated:true, completion: nil)
    

    Now call like this

    alertWithTF(title: "This is title", message: "This is message")
    

提交回复
热议问题