How to add TextField to UIAlertController in Swift

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

    To add alertController with one textField (Swift 5)

    func openAlert(){
        let alertController = UIAlertController(title: "Title", message: "", preferredStyle: .alert)
        alertController.addTextField { (textField : UITextField!) -> Void in
            textField.placeholder = "Enter name"
        }
    
        let saveAction = UIAlertAction(title: kAlertConfirm, style: .default, handler: { alert -> Void in
            if let textField = alertController.textFields?[0] {
                if textField.text!.count > 0 {
                    print("Text :: \(textField.text ?? "")")
                }
            }
        })
    
        let cancelAction = UIAlertAction(title: kAlertCancel, style: .default, handler: {
            (action : UIAlertAction!) -> Void in })
    
        alertController.addAction(cancelAction)
        alertController.addAction(saveAction)
    
        alertController.preferredAction = saveAction
    
        self.present(alertController, animated: true, completion: nil)
    }
    

提交回复
热议问题