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

最后都变了- 提交于 2019-11-30 02:14:10

问题


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)

回答1:


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

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



回答2:


Swift 3:

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


来源:https://stackoverflow.com/questions/28594086/how-to-have-a-numberpad-in-a-textfield-of-an-alert-controller-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!