如何在警告控制器的文本字段中添加数字键盘 [Swift]

20

我正在尝试调用一个带有文本字段的警报控制器。但是我想立即显示数字键盘,因为用户只能输入数字。我尝试了以下代码,但它不起作用。

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)
2个回答

34

我自己找到了!这可能对其他人有用。

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

1
现在应该是 UIKeyboardType.numberPad - Michael Volo

7

Swift 3:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接