How to add TextField to UIAlertController in Swift

前端 未结 13 727
余生分开走
余生分开走 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:25

    Solution:

    Swift 4.2

    Try the following lines and see if it works:

    let alertController = UIAlertController(title: "Add New Name", message: "", preferredStyle: .alert)
    
    alertController.addTextField { (textField : UITextField!) -> Void in
        textField.placeholder = "Enter Second Name"
    }
    
    let saveAction = UIAlertAction(title: "Save", style: .default, handler: { alert -> Void in
        let firstTextField = alertController.textFields![0] as UITextField
        let secondTextField = alertController.textFields![1] as UITextField
    })
    
    let cancelAction = UIAlertAction(title: "Cancel", style: .default, handler: nil )
    
    alertController.addTextField { (textField : UITextField!) -> Void in
        textField.placeholder = "Enter First Name"
    }
    
    alertController.addAction(saveAction)
    alertController.addAction(cancelAction)
    
    self.present(alertController, animated: true, completion: nil)
    

    Hope it helps.

提交回复
热议问题