我目前正在创建一个包含UITextFields的应用程序,并且它们已经按预期工作但是当我最近测试我的应用程序时,我注意到在我按下UITextField后键盘没有被忽略。当我点击离开或按下返回时,它的行为像正常解雇一样,但现在我无法做任何让它解雇的事情?
这是我当前的ViewController代码:
import UIKit
class CreateNewBudgetVC: UIViewController {
@IBOutlet weak var grossIncomeVal: UITextField!
@IBOutlet weak var locationVal: UITextField!
@IBOutlet weak var federalExptVal: UITextField!
@IBOutlet weak var stateExptVal: UITextField!
@IBOutlet weak var deductionsList: UITableView!
@IBAction func cancelPressed(_ sender: Any) {
performSegue(withIdentifier: "CancelSegue", sender: self)
}
@IBAction func generateBudgetPressed(_ sender: Any) {
let budget = Budget(grossIncome: Int(grossIncomeVal.text!)!)
performSegue(withIdentifier: "GenerateSegue", sender: budget)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let budget = sender as? Budget, let destination = segue.destination as? BudgetVC {
destination.budget = budget
}
}
}
答案 0 :(得分:2)
只需使用
self.view.endEditing(true)
在上面定义的操作方法中,您要关闭键盘。
例如
@IBAction func cancelPressed(_ sender: Any) {
self.view.endEditing(true)
performSegue(withIdentifier: "CancelSegue", sender: self)
}
如果您想在键盘的return tap
中返回键盘,请使用此
class ViewController: UIViewController,UITextFieldDelegate
并实现委托方法
func textFieldShouldReturn(_ textField: UITextField) -> Bool { //delegate method
textField.resignFirstResponder()
return true
}
但请勿忘记分配delegate to textfield
yourTextField.delegate = self in `viewDidLoad`
如果您想在外面点按时关闭键盘,只需为您的视图指定一个点击手势
在ViewDidload中
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(self.dismissKeyboard (_:)))
self.view.addGestureRecognizer(tapGesture)
实施解雇功能
func dismissKeyboard (_ sender: UITapGestureRecognizer) {
self.view.endEditing(true)
}