[英]iOS - close keyboard when button is pressed
I currently have a textfield
, a picker
, a button
, and several textviews
/ labels
. 我目前有一个
textfield
,一个picker
,一个button
和几个textviews
/ labels
。
The textfield
prompts a number only keyboard, I want the keyboard to dismiss when the one button is pressed. textfield
提示仅数字键盘,我希望在按下一个按钮时关闭键盘。
Here is a snippet of some of the code: 这是一些代码的片段:
class ViewController: UIViewController, UITextFieldDelegate, UIPickerViewDataSource, UIPickerViewDelegate {
@IBOutlet weak var provincePicker: UIPickerView!
@IBOutlet weak var calcButton: UIButton!
@IBOutlet weak var incomeLabel: UITextView!
@IBOutlet weak var salaryTextField: UITextField!
@IBOutlet weak var beforeTax: UITextView!
@IBOutlet weak var provincialTax: UITextView!
@IBOutlet weak var federalTax: UITextView!
@IBOutlet weak var afterTax: UITextView!
... ...
override func viewDidLoad() {
// numberOnly()
borders()
super.viewDidLoad()
provincePicker.dataSource = self
provincePicker.delegate = self
}
... ...
@IBAction func calculateButton(sender: UIButton) {
let formatter = NSNumberFormatter()
formatter.numberStyle = NSNumberFormatterStyle.CurrencyStyle
formatter.locale = NSLocale(localeIdentifier: "en_CA")
let index = provincePicker.selectedRowInComponent(0)
switch(index) {
case 0:
calculate(abBrackets, rates: abRates) //AB
//cutting out code here
dismissKeyboard()
}
func dismissKeyboard() {
self.view.endEditing(true)
}
Try to call this function when your button is pressed: 尝试在按下按钮时调用此函数:
func dismissKeyboard() {
self.view.endEditing(true)
}
Or, in your button function, do this: 或者,在您的按钮功能中,执行以下操作:
@IBAction func button(sender: UIButton) {
self.view.endEditing(true)
}
And remember to connect your button to your viewController by control + click on your button and drag it to your controller file, then, on the popup, click on connection
and select action
and give it a name: 并记住要通过控制将按钮连接到viewController并单击按钮并将其拖动到控制器文件,然后在弹出窗口中单击
connection
并选择action
并为其命名:
Also, check if you have multiple connection on your button, it might be a problem... 另外,请检查您的按钮上是否有多个连接,这可能是一个问题...
You just want to end editing when the button is clicked. 您只想在单击按钮时结束编辑。
You can do that by calling the endEditing(force: Bool)
function: 您可以通过调用
endEditing(force: Bool)
函数来做到这一点:
which causes the view (or one of its embedded text fields) to resign the first responder status. 这会使视图(或其嵌入的文本字段之一)退出第一响应者状态。
Use like this: 像这样使用:
@IBAction func didTapBtn(sender: UIButton) {
self.view.endEditing(true)
}
首先,CTRL-DRAG一个目标动作(或以编程方式使用addTarget ...函数)。其次,在代码中执行以下操作:
self.inputTextField.resignFirstResponder()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.