我想在点击屏幕上的任何位置时关闭键盘。为此,我使用了touchbegan
方法,但没有调用此方法。
答案 0 :(得分:1)
您需要指定UITapGestureRecogniser
来查看和关闭键盘。
在viewdidLoad()
中let tap = UITapGestureRecognizer.init(target: self, action: #selector(self.dismissKeybord(_:)))
tap.numberOfTapsRequired = 1
self.view.addGestureRecognizer(tap)
在dismissKeybord
func dismissKeybord(_ sender:UITapGestureRecognizer) {
self.view.endEditing(true)
}
答案 1 :(得分:0)
为我工作。显示键盘与textfields
的联系。隐藏其他所有内容。
class LoginController: UIViewController, UITextFieldDelegate {
@IBOutlet weak var userLogin: UITextField!
@IBOutlet weak var userPassword: UITextField!
override func viewDidLoad() {
userLogin.delegate = self
userPassword.delegate = self
//For scrolling the view if keyboard on
NotificationCenter.default.addObserver(self, selector: #selector(LoginController.keyboardWillShow),
name: NSNotification.Name.UIKeyboardWillShow, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(LoginController.keyboardWillHide),
name: NSNotification.Name.UIKeyboardWillHide, object: nil)
super.viewDidLoad()
}
// OTHER METHODS
var keyBoardAlreadyShowed = false //using this to not let app to scroll view
//if we tapped UITextField and then another UITextField
func keyboardWillShow(notification: NSNotification) {
if !keyBoardAlreadyShowed {
view.frame.origin.y -= 50
keyBoardAlreadyShowed = true
}
}
func keyboardWillHide(notification: NSNotification) {
view.frame.origin.y += 50
keyBoardAlreadyShowed = false
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
view.endEditing(true)
}
}
您需要设置delegates
和observers
答案 2 :(得分:0)
如果您的触摸不被其他视图吃掉,那么我想这会起作用
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
if touches.first != nil {
view.endEditing(true)
}
}
答案 3 :(得分:0)
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
self.view.endEditing(true)
}
答案 4 :(得分:0)
最近我的案子很有用。也应该适合你。
(请注意,参数true是动画的值)
class MyViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let tapGestureRecognizer = UITapGestureRecognizer(target: self, action:#selector(endEditing))
tapper.cancelsTouchesInView = false
self.view.addGestureRecognizer(tapGestureRecognizer)
}
func endEditing() {
self.view.endEditing(true)
}
}