如何在没有文本框的情况下显示数字键盘

问题描述:

你好我正在尝试在定时器启动后出现数字键盘。然后将我的用户类型号码放在键盘上,并将其输入保存到代码中的变量中,而不是文本框中。我似乎无法找到任何关于在不使用文本框的情况下弹出数字键盘的任何信息。任何帮助表示赞赏。如何在没有文本框的情况下显示数字键盘

+1

到目前为止,您的代码在哪里? – Adrianopolis

好吧,我会给你一些代码,这将对你有很大的帮助。您需要某种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://*.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) 
    } 
+0

注意:这是使用'.phonePad'类型的键盘,它没有'.'字符。这意味着用户输入必须是一个整数,这就是为什么我这样做。如果您需要十进制数字,则需要切换键盘类型,并将文本从文本字段转换为双精度或浮点数。 – NSGangster

我使用情节串连图板,这是我做过什么:

  1. 拖放一个文本字段
  2. 在故事板,在属性检查器(在选择文本字段),下“绘图”,选择隐藏
  3. 使文本字段的出口在您的视图控制器
  4. 确保您的视图控制器扩展了UITextViewDelegate
  5. 让你的当前视图控制器的委托
  6. 在居民点的只需拨打< textfieldOutlet> .becomeFirstResponder()

现在,这是一个简单的文本字段的数据,美国可以随时存储的值并在其他地方使用它。

+0

你能够得到这个工作? – Karthik