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

时间:2017-05-18 23:05:03

标签: swift textbox

你好我试图在计时器启动后出现一个数字键盘。然后将我的用户类型编号放在打击垫上,并将其输入保存到我的代码中的变量而不是文本框中。我似乎无法在不使用文本框的情况下弹出数字键盘。任何帮助表示赞赏。

2 个答案:

答案 0 :(得分:0)

好的我会给你一些能帮到你的代码。您需要某种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)
    }

答案 1 :(得分:0)

我正在使用故事板,这就是我所做的:

  1. 拖放文本字段
  2. 在故事板上,在属性检查器中(选择了文本字段),在"绘图"下,选择隐藏
  3. 为视图控制器中的文本字段设置插座
  4. 确保您的视图控制器扩展了UITextViewDelegate
  5. 使您当前的视图控制器成为委托
  6. 所需位置,只需调用< textfieldOutlet > .becomeFirstResponder()
  7. 既然这只是一个文本字段的数据,你可以随时存储该值并将其用于其他地方。