简体   繁体   中英

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)

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

alert.addTextField(configurationHandler: { textField in
    textField.keyboardType = .numberPad
})

Swift 3:

alert.addTextField { (textField) in
    textField.keyboardType = .decimalPad
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM