Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to have a numberpad in a textfield of an alert controller [swift]

I'm trying to call an alert controller which has a textfield. But I'd like to show immediately the numberpad since the user should input numbers only. I tried with the following but it does not work.

let alert = UIAlertController(title: "New Rating", message: "Rate this!", preferredStyle: UIAlertControllerStyle.Alert)

  let cancelAction = UIAlertAction(title: "Cancel", style: .Default, handler: { (action: UIAlertAction!) in })

  let saveAction = UIAlertAction(title: "Save", style: .Default, handler: { (action: UIAlertAction!) in

    let textField = alert.textFields![0] as UITextField
    textField.keyboardType = UIKeyboardType.NumberPad

    self.updateRating(textField.text)
  })

  alert.addTextFieldWithConfigurationHandler { (textField: UITextField!) in }

  alert.addAction(cancelAction)
  alert.addAction(saveAction)

  self.presentViewController(alert, animated: true, completion: nil)
like image 269
Nicholas Avatar asked Feb 18 '15 21:02

Nicholas


People also ask

How do you add a TextField to an alert?

We can have a text field in an alert by using TextField or SecureField as action content. We add text field in actions , not message . Text("Please enter your username and password.") TextField and SecureField are supported in iOS 16.


2 Answers

Found it on my own! It might be useful for someone else.

alert.addTextField(configurationHandler: { textField in
    textField.keyboardType = .numberPad
})
like image 126
Nicholas Avatar answered Sep 27 '22 22:09

Nicholas


Swift 3:

alert.addTextField { (textField) in
    textField.keyboardType = .decimalPad
}
like image 26
RawMean Avatar answered Sep 27 '22 20:09

RawMean