Prevent keyboard from opening automatically using UIAlertController

I have a UIAlertController (Alert style) style in Swift and everything works fine. However, the UITextField that I added to it is an optional field in which the user does not need to enter text. The problem is that when I show this UIAlertController , the keyboard appears at the same time as the default text box. I do not want the keyboard to appear unless the user has pressed UITextField . How can I do that?

  let popup = UIAlertController(title: "My title", message: "My message", preferredStyle: .Alert) popup.addTextFieldWithConfigurationHandler { (optionalTextField) -> Void in optionalTextField.placeholder = "This is optional" } let submitAction = UIAlertAction(title: "Submit", style: .Cancel) { (action) -> Void in let optionalTextField = popup.textFields![0] let text = optionalTextField.text print(text) } let cancelAction = UIAlertAction(title: "Cancel", style: .Default, handler: nil) popup.addAction(cancelAction) popup.addAction(submitAction) self.presentViewController(popup, animated: true, completion: nil) 
+5
source share
2 answers

this should do the trick:

Make your viewController compatible with UITextFieldDelegate

assign popup.textFields![0].delegate self

add a unique tag to popup.textFields![0] (I used 999 in the example below)

realize it

 func textFieldShouldBeginEditing(textField: UITextField) -> Bool { if textField.tag == 999 { textField.tag = 0 return false }else{ return true } } 

your code should look like this:

  let popup = UIAlertController(title: "My title", message: "My message", preferredStyle: .Alert) popup.addTextFieldWithConfigurationHandler { (optionalTextField) -> Void in optionalTextField.placeholder = "This is optional" } popup.textFields![0].delegate = self popup.textFields![0].tag = 999 let submitAction = UIAlertAction(title: "Submit", style: .Cancel) { (action) -> Void in let optionalTextField = popup.textFields![0] let text = optionalTextField.text print(text) } let cancelAction = UIAlertAction(title: "Cancel", style: .Default, handler: nil) popup.addAction(cancelAction) popup.addAction(submitAction) self.presentViewController(popup, animated: true, completion: nil) 
+4
source

I think this is the default behavior for textField in the alert, maybe consider an alternative design so that the text box only displays when needed ...

Now you can get around this with this!

When you add textField, make your viewController delegation and add a tag to it.

eg,

 popup.addTextFieldWithConfigurationHandler { (optionalTextField) -> Void in optionalTextField.placeholder = "This is optional" optionalTextField.delegate = self optionalTextField.tag = -1 } 

then we implement textFieldShouldBeginEditing ()

 func textFieldShouldBeginEditing(textField: UITextField!) { if textField.tag == -1 { textField.tag = 0 return false } else { return true } } 
+3
source

Source: https://habr.com/ru/post/1247637/


All Articles