How to add TextField to UIAlertController in Swift

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

    Swift5

    First class conforms to the UITextFieldDelegate , then create new textField property

        private var myTextField : UITextField?
    
        // now where u want to add code
        let alertContoller = UIAlertController.init(title: "Add", message: "My message to user", preferredStyle: .alert)
        alertContoller.addTextField { (textField) in
            // make sure your outside any property should be accessed with self here
            self.myTextField = textField
            //Important step assign textfield delegate to self
            self.myTextField?.delegate = self 
            self.myTextField?.placeholder = self.textFieldPlaceholderText
        }
        let action = UIAlertAction.init(title: "Ok", style: .default) { action in
            print("Alert tapped")
        }
        alertContoller.addAction(action)
        present(alertContoller, animated: true, completion:nil)
    

    Thanks

提交回复
热议问题