【问题标题】:How to make a number pad appear without a text box如何使数字键盘出现没有文本框
【发布时间】:2017-10-18 22:30:08
【问题描述】:

您好,我正在尝试在计时器到时后出现数字键盘。然后让我的用户在键盘上键入数字,并将他们的输入保存到我的代码中的变量而不是文本框中。如果不使用文本框,我似乎找不到任何弹出数字键盘的内容。任何帮助表示赞赏。

【问题讨论】:

  • 到目前为止你的代码在哪里?

标签: swift textbox


【解决方案1】:

好的,我将为您提供一些对您有很大帮助的代码。您需要某种 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 类型键盘。这意味着用户输入必须是整数,这就是我将其转换为整数的原因。如果您需要十进制数字,则需要切换键盘类型并将文本从文本字段转换为双精度或浮点数。
【解决方案2】:

我正在使用情节提要,这就是我所做的:

  1. 拖放文本字段
  2. 在情节提要的属性检查器中(已选择文本字段),在“绘图”下,选择隐藏
  3. 为视图控制器中的文本字段创建一个出口
  4. 确保您的视图控制器扩展了 UITextViewDelegate
  5. 将您当前的视图控制器设为委托
  6. 所需位置只需调用textfieldOutlet>.becomeFirstResponder()

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-29
    • 1970-01-01
    • 2012-04-28
    • 2011-04-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多