在我的登录页面上,如果我专注于UITextEdit输入电子邮件和密码,键盘会出现,登录页面向上滚动。如果我触摸键盘外部,我会添加删除键盘的代码。
extension UIViewController {
func hideKeyboardWhenTappedAround() {
let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(UIViewController.dismissKeyboard))
tap.cancelsTouchesInView = false
view.addGestureRecognizer(tap)
}
@objc func dismissKeyboard() {
view.endEditing(true)
UIView.animate(withDuration: 0.3, animations: {
self.view.frame = CGRect(x: 0, y: 0, width: self.view.frame.width, height: self.view.frame.height)
})
}
}
在我的viewDidLoad()函数中,我像这样添加了它。
override func viewDidLoad()
{
super.viewDidLoad()
//TODO
self.hideKeyboardWhenTappedAround()
...
}
它工作得很好,但是如果我在键盘仍然打开的时候单击登录按钮,辞退键盘()函数可以工作,但是btnClick函数不能工作。
@IBAction func LoginBtnClick(_ sender: Any)
{
print("loginBtn")
//...
}
我该如何解决这个问题?
发布于 2018-01-11 16:35:52
我使用以下代码对其进行了测试:
import UIKit
extension UIViewController {
func hideKeyboardWhenTappedAround() {
let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(UIViewController.dismissKeyboard))
tap.cancelsTouchesInView = false
view.addGestureRecognizer(tap)
}
@objc func dismissKeyboard() {
view.endEditing(true)
UIView.animate(withDuration: 0.3, animations: {
self.view.frame = CGRect(x: 0, y: 0, width: self.view.frame.width, height: self.view.frame.height)
})
}
}
class ViewController: UIViewController {
fileprivate let textField = UITextField(frame: CGRect(x: 0, y: 0, width: 400, height: 50))
fileprivate let button = UIButton(frame: CGRect(x: 20, y: 200, width: 150, height: 50))
override func loadView() {
super.loadView()
view.addSubview(textField)
textField.backgroundColor = .lightGray
view.addSubview(button)
button.setTitle("Press me", for: .normal)
button.setTitleColor(UIColor.blue, for: .normal)
button.addTarget(self, action: #selector(a), for: .touchUpInside)
hideKeyboardWhenTappedAround()
}
@objc func a() {
print(">>>> pressed")
}
}
调用a
中的代码。因此,我假设代码中还有其他东西会导致按钮不工作。也许您忘了将button
链接到@IBAction
LoginBtnClick(_:)
--检查连接是否真的存在。
https://stackoverflow.com/questions/48211042
复制相似问题