How to add TextField to UIAlertController in Swift

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

    UIAlertController with UITextfield in latest Apple Swift version 5.1.3

    Create a lazy variable of UIAlertController in your UIViewController , Add UITextFieldDelegate , Show Alert on UIButton Action :

    class  YourViewController: UIViewController,UITextFieldDelegate {
    
        //Create Alert Controller Object here
        lazy var alertEmailAddEditView:UIAlertController = {
    
            let alert = UIAlertController(title:"My App", message: "Customize Add/Edit Email Pop Up", preferredStyle:UIAlertController.Style.alert)
    
            //ADD TEXT FIELD (YOU CAN ADD MULTIPLE TEXTFILED AS WELL)
            alert.addTextField { (textField : UITextField!) in
                textField.placeholder = "Enter  emails"
                textField.delegate = self
            }
    
            //SAVE BUTTON
            let save = UIAlertAction(title: "Save", style: UIAlertAction.Style.default, handler: { saveAction -> Void in
                let textField = alert.textFields![0] as UITextField
                print("value entered by user in our textfield is: \(textField.text)")
            })
            //CANCEL BUTTON
            let cancel = UIAlertAction(title: "Cancel", style: UIAlertAction.Style.default, handler: {
                (action : UIAlertAction!) -> Void in })
    
    
            alert.addAction(save)
            alert.addAction(cancel)
    
            return alert
        }()
    
    
        //MARK:- UIButton Action for showing Alert Controller
        @objc func buttonClicked(btn:UIButton){
            self.present(alertEmailAddEditView, animated: true, completion: nil)
        }
    
        //MARK:- UITextFieldDelegate
        func textFieldShouldReturn(_ textField: UITextField) -> Bool {
            textField.resignFirstResponder()
            return true
        }
    }
    

    Happy Coding!! :)

提交回复
热议问题