【发布时间】:2017-10-18 22:30:08
【问题描述】:
您好,我正在尝试在计时器到时后出现数字键盘。然后让我的用户在键盘上键入数字,并将他们的输入保存到我的代码中的变量而不是文本框中。如果不使用文本框,我似乎找不到任何弹出数字键盘的内容。任何帮助表示赞赏。
【问题讨论】:
-
到目前为止你的代码在哪里?
您好,我正在尝试在计时器到时后出现数字键盘。然后让我的用户在键盘上键入数字,并将他们的输入保存到我的代码中的变量而不是文本框中。如果不使用文本框,我似乎找不到任何弹出数字键盘的内容。任何帮助表示赞赏。
【问题讨论】:
好的,我将为您提供一些对您有很大帮助的代码。您需要某种 UITextView 或 UITextField 来获取系统键盘。所以本质上我们要做的是有一个 textField 而不显示它,然后从中获取信息并将其存储到变量中。
//Dummy textField instance as a VC property.
let textField = UITextField()
//Add some setup to viewDidLoad
override func viewDidLoad() {
super.viewDidLoad()
textField.delegate = self //Don't forget to make vc conform to UITextFieldDelegateProtocol
textField.keyboardType = .phonePad
//http://stackoverflow.com/a/40640855/5153744 for setting up toolbar
let keyboardToolbar = UIToolbar()
keyboardToolbar.sizeToFit()
let flexBarButton = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
let doneBarButton = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(dismissKeyboard))
keyboardToolbar.items = [flexBarButton, doneBarButton]
textField.inputAccessoryView = keyboardToolbar
//You can't get the textField to become the first responder without adding it as a subview
//But don't worry because its frame is 0 so it won't show.
self.view.addSubview(textField)
}
//When done button is pressed this will get called and initate `textFieldDidEndEditing:`
func dismissKeyboard() {
view.endEditing(true)
}
//This is the whatever function you call when your timer is fired. Important thing is just line of code inside that our dummy code becomes first responder
func timerUp() {
textField.becomeFirstResponder()
}
//This is called when done is pressed and now you can grab value out of the textField and store it in any variable you want.
func textFieldDidEndEditing(_ textField: UITextField) {
textField.resignFirstResponder()
let intValue = Int(textField.text ?? "0") ?? 0
print(intValue)
}
【讨论】:
. 字符的.phonePad 类型键盘。这意味着用户输入必须是整数,这就是我将其转换为整数的原因。如果您需要十进制数字,则需要切换键盘类型并将文本从文本字段转换为双精度或浮点数。
我正在使用情节提要,这就是我所做的:
现在这只是一个文本字段的数据,您可以随时存储该值并在其他地方使用它。
【讨论】: