xcode 当用户单击视图背景时,如何使键盘消失?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10289533/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I make the keyboard go away when a user clicks on the background of the view?
提问by Justin Copeland
I have a UITextField in my iOS app. When a user enters text and clicks Return, the keyboard goes away due to a call to an IBAction with "resignFirstResponder."
我的 iOS 应用中有一个 UITextField。当用户输入文本并单击 Return 时,由于使用“resignFirstResponder”调用 IBAction,键盘会消失。
However, XCode does not let me drag a line from the UIView itself to File Owner. How do I associate touching the background of a UIView with an IBAction that makes the keyboard go away?
但是,XCode 不允许我从 UIView 本身拖一条线到文件所有者。如何将触摸 UIView 的背景与使键盘消失的 IBAction 相关联?
回答by code007
You can use UITapGestureRecognizer. see: Dismiss keyboard by touching background of UITableView
您可以使用 UITapGestureRecognizer。请参阅:通过触摸 UITableView 的背景来关闭键盘
so instead of tableview, just add it to your view instead:
所以代替tableview,只需将其添加到您的视图中:
UITapGestureRecognizer *gestureRecognizer = [[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hideKeyboard)] autorelease];
gestureRecognizer.cancelsTouchesInView = NO; //so that action such as clear text field button can be pressed
[self.view addGestureRecognizer:gestureRecognizer];
and have a method to hide your keyboard
并有一种隐藏键盘的方法
- (void) hideKeyboard {
[self.view endEditing:YES];
}
回答by Abizern
You've already noticed that you can't drag from the UIView to the file's owner to assoctiate an action with a touch.
您已经注意到您不能从 UIView 拖动到文件的所有者以将操作与触摸相关联。
The way to work around this is to change the class of the background view from UIView
to UIControl
and hook up an action from there to a method in your controller to stop editing.
解决此问题的方法是将背景视图的类从 更改为UIView
,UIControl
并将从那里的操作连接到控制器中的方法以停止编辑。
That's because a UIControl can respond to touch events, and a UIView does not, but a UIControl subclasses UIView, and so it can be used in place of a UIView.
这是因为 UIControl 可以响应触摸事件,而 UIView 不能,但 UIControl 是 UIView 的子类,因此它可以代替 UIView 使用。
I wrote an example projecta while ago that uses this technique. Have a look at the secondViewController
's xib file and see how I've change the class of the background view and hooked it up to a an action in the controller to dismiss the keyboard.
不久前我写了一个使用这种技术的示例项目。查看secondViewController
xib 文件,看看我如何更改背景视图的类并将其连接到控制器中的一个动作以关闭键盘。
回答by Richard Shergold
Use the touchesBegan with Event and end editing on the view:
在视图上使用 touchesBegan 和 Event 并结束编辑:
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
[self.view endEditing:YES];
}
回答by Edu
One easy way to do it is to create a big transparent UIButton behind the view.
一种简单的方法是在视图后面创建一个大的透明 UIButton。