当点击键盘外部时,如何从UITextField中解除键盘。我试过了resignFirstResponder()
,它只在输入一个数字后退出。我也试过textField.inputView = UIView.frame(frame: CGRectZero)
。我已经看到了很多Obj-C对我要问的问题,但是我需要Swift等价物,因为我在Objective-C中没有编程经验
感谢您的时间和耐心。
答案 0 :(得分:15)
向视图添加点击手势识别器并调用resignFirstResponder()或self.view.endEditing(true)的最佳方法。我更喜欢endEditing(),因为必须分别为每个文本字段完成resignFirstResponder,这与为视图本身完成的endEditing不同。
在viewDidLoad中,编写以下代码:
let tapRecognizer = UITapGestureRecognizer()
tapRecognizer.addTarget(self, action: "didTapView")
self.view.addGestureRecognizer(tapRecognizer)
现在编写didTapView方法来关闭键盘:
func didTapView(){
self.view.endEditing(true)
}
现在当您在控制器的主视图上点击键盘外部时,它将调用didTapView方法并关闭键盘。
Swift 3.x
viewDidLoad中的代码应为:
let tapRecognizer = UITapGestureRecognizer()
tapRecognizer.addTarget(self, action: #selector(ViewController.didTapView))
self.view.addGestureRecognizer(tapRecognizer)
其中ViewController应该是视图控制器的名称。
由于
答案 1 :(得分:4)
Swift 3测试并正常工作
// dismiss keyboard on touch outside textfield
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
for txt in self.view.subviews {
if txt.isKind(of: UITextField.self) && txt.isFirstResponder {
txt.resignFirstResponder()
}
}
}
<强>享受强>
Swift 2.3测试并正常工作
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
for txt in self.view.subviews {
if txt.isKindOfClass(UITextField.self) && txt.isFirstResponder() {
txt.resignFirstResponder()
}
}
}
<强>享受强>
答案 2 :(得分:2)
按“返回”
时,您也可以使用此方法关闭键盘func textFieldShouldReturn(textField: UITextField!) -> Bool {
self.view.endEditing(true);
return false;
}
确保设置代理
答案 3 :(得分:0)
如果您不想定义额外的方法,有一种稍微简单的方法也可以使用
let tapRecognizer = UITapGestureRecognizer(target: self, action: "endEditing:")
view.addGestureRecognizer(tapRecognizer)
答案 4 :(得分:0)
我在一个网站上找到了此代码,对我来说非常有用!
//FUNCTION TO DISMISS THE KEYBOARD
func initializeHideKeyboard(){
//Declare a Tap Gesture Recognizer which will trigger our dismissMyKeyboard() function
let tap: UITapGestureRecognizer = UITapGestureRecognizer(
target: self,
action: #selector(dismissMyKeyboard))
//Add this tap gesture recognizer to the parent view
view.addGestureRecognizer(tap)
}
@objc func dismissMyKeyboard(){
//endEditing causes the view (or one of its embedded text fields) to resign the first responder status.
//In short- Dismiss the active keyboard.
view.endEditing(true)
}
然后只需在按钮操作或类似操作中调用此函数:
dismissMyKeyboard()