2017-05-18 78 views
0

你好我正在嘗試在定時器啓動後出現數字鍵盤。然後將我的用戶類型號碼放在鍵盤上,並將其輸入保存到代碼中的變量中,而不是文本框中。我似乎無法找到任何關於在不使用文本框的情況下彈出數字鍵盤的任何信息。任何幫助表示讚賞。如何在沒有文本框的情況下顯示數字鍵盤

+1

到目前爲止,您的代碼在哪裏? – Adrianopolis

回答

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) 
    } 
+0

注意:這是使用'.phonePad'類型的鍵盤,它沒有'.'字符。這意味着用戶輸入必須是一個整數,這就是爲什麼我這樣做。如果您需要十進制數字,則需要切換鍵盤類型,並將文本從文本字段轉換爲雙精度或浮點數。 – NSGangster

0

我使用情節串連圖板,這是我做過什麼:

  1. 拖放一個文本字段
  2. 在故事板,在屬性檢查器(在選擇文本字段),下「繪圖」,選擇隱藏
  3. 使文本字段的出口在您的視圖控制器
  4. 確保您的視圖控制器擴展了UITextViewDelegate
  5. 讓你的當前視圖控制器的委託
  6. 在居民點的只需撥打< textfieldOutlet> .becomeFirstResponder()

現在,這是一個簡單的文本字段的數據,美國可以隨時存儲的值並在其他地方使用它。

+0

你能夠得到這個工作? – Karthik

相關問題