ios 如何通过点击任意位置来关闭数字键盘
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6991085/
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 to dismiss number pad keyboard by tapping anywhere
提问by jsanmtosj
I'd like to know the simplest code to dismiss the number pad keyboard when tapping anywhere outside the number pad. It's a simple application to input a number inside a text field and then a user can dismiss the keyboard after the user finishes typing the numbers on the text field. Thanks! :)
我想知道在点击数字键盘外的任何地方时关闭数字键盘键盘的最简单代码。这是一个简单的应用程序,可以在文本字段中输入数字,然后在用户完成在文本字段中输入数字后关闭键盘。谢谢!:)
回答by Filip Radelic
Declaring the text field as instance variable or property if it isn't already and implementing a simple method like this:
将文本字段声明为实例变量或属性(如果尚未实现)并实现如下简单方法:
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
[textField resignFirstResponder];
}
will do just fine.
会做的很好。
回答by Gajendra K Chauhan
Try this method,
试试这个方法,
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
[self.view endEditing:YES];
}
Now tap anywhere and see keyboard will dismiss. :-)
现在点击任何地方,然后键盘就会消失。:-)
回答by abdul sathar
回答by rptwsthi
Touching the Background to Close the Keyboard
触摸背景关闭键盘
Go to Xcode if you're not already there. We need to add one more action to our controller class. Add the following line to your Control_FunViewController.h file:
如果您还没有在那里,请转到 Xcode。我们需要在控制器类中再添加一个动作。将以下行添加到您的 Control_FunViewController.h 文件中:
#import <UIKit/UIKit.h>
@interface Control_FunViewController : UIViewController {
UITextField *nameField;
UITextField *numberField;
}
@property (nonatomic, retain) IBOutlet UITextField *nameField; ]
@property (nonatomic, retain) IBOutlet UITextField *numberField;
- (IBAction)textFieldDoneEditing:(id)sender;
- (IBAction)backgroundTap:(id)sender;
@end
Save the header file; switch over to the implementation file, and add this code, which simply tells both text fields to yield first responder status if they have it. It is perfectly safe to call resignFirstResponder on a control that is not the first responder, so we can safely call it on both text fields without having to check whether either is the first responder.
保存头文件;切换到实现文件,并添加此代码,它只是告诉两个文本字段,如果它们具有第一响应者状态,则产生第一响应者状态。在不是第一响应者的控件上调用 resignFirstResponder 是完全安全的,因此我们可以安全地在两个文本字段上调用它,而不必检查其中一个是否是第一响应者。
- (IBAction)backgroundTap:(id)sender {
[nameField resignFirstResponder];
[numberField resignFirstResponder];
}
TIP Save this file, and go back to Interface Builder. We now need to change the underlying class of our nib's view. If you look at the nib's main window , you'll see that there are three icons in that view. The third one, called View, is our nib's main view that holds all the other controls and views as subviews. Single-click the icon called View, which represents our nib's container view. Press ?4 to bring up the identity inspector. This is where we can change the underlying class of any object instance in Interface Builder.
提示保存此文件,然后返回到 Interface Builder。我们现在需要更改笔尖视图的基础类。如果您查看笔尖的主窗口,您会看到该视图中有三个图标。第三个叫做 View,是我们 nib 的主视图,它包含所有其他控件和视图作为子视图。单击名为 View 的图标,它代表我们的 nib 的容器视图。按?4 调出身份检查器。这是我们可以在 Interface Builder 中更改任何对象实例的基础类的地方。
You'll be switching between header and implementation files a lot as you code. Fortunately, Xcode has a key combination that will switch you between these files quickly. The default key combination is ??? (option-command-up arrow), although you can change it to anything you want using Xcode's preferences.76
在编写代码时,您将在头文件和实现文件之间切换很多次。幸运的是,Xcode 有一个组合键,可以让您在这些文件之间快速切换。默认组合键是???(选项命令向上箭头),尽管您可以使用 Xcode 的首选项将其更改为您想要的任何内容。 76
The field labeled Class currently says UIView. Change it to read UIControl. All controls that are capable of trig- gering action methods are subclasses of UIControl, so by changing the underlying class, we have just given this view the ability to trigger action methods. You can verify this by pressing ?2 to bring up the connections inspector.
标记为 Class 的字段当前显示 UIView。将其更改为读取 UIControl。所有能够触发动作方法的控件都是 UIControl 的子类,所以通过改变底层类,我们刚刚赋予了这个视图触发动作方法的能力。您可以通过按 ?2 调出连接检查器来验证这一点。
Drag from the Touch Down event to the File's Owner icon, and choose the backgroundTap:action. Now, touches anywhere in the view without an active control will trigger our new action method, which will cause the keyboard to retract.
从 Touch Down 事件拖到 File's Owner 图标,然后选择backgroundTap:操作。现在,在没有活动控件的情况下触摸视图中的任何地方将触发我们的新操作方法,这将导致键盘缩回。
NOTE Save the nib, and let's go back and try it. Compile and run your application again. This time, the keyboard should disappear not only when the Done button is tapped but also when you click anywhere that's not an active control, which is the behavior that your user will expect.
注意保存笔尖,让我们回去试试。再次编译并运行您的应用程序。这一次,键盘应该不仅在点击完成按钮时消失,而且在您单击非活动控件的任何地方时也会消失,这是您的用户所期望的行为。
回答by mbm29414
I tried implementing some of the solutions here and found that there were some issues with them. Notably, My UIView
contains a UIScrollView
, which appears to intercept touches.
我尝试在这里实施一些解决方案,发现它们存在一些问题。值得注意的是, MyUIView
包含一个UIScrollView
,它似乎可以拦截触摸。
When that failed, I considered that "tapping anywhere" is a little bit of an unspecified behavior, requiring the user to guess how to dismiss the keyboard instead of giving them clear guidance.
当那失败时,我认为“在任何地方敲击”是一种未指定的行为,需要用户猜测如何关闭键盘而不是给他们明确的指导。
Also, I have a "Return" or "Done" button on every other keyboard I show in the app, so I was determined to give the user an easy, intuitive, clearly-specified way to dismiss the keyboard with a Number Pad that was in line with the other keyboard dismissal mechanisms in use.
此外,我在应用程序中显示的每个其他键盘上都有一个“返回”或“完成”按钮,因此我决定为用户提供一种简单、直观、明确指定的方式来关闭带有数字键盘的键盘与正在使用的其他键盘解除机制一致。
I realize that this isn't what the OP is specifically requesting, but I believe it to be a better solution than the "tap anywhere" request (and it's easy to implement!).
我意识到这不是 OP 所特别要求的,但我相信它是比“点击任何地方”请求更好的解决方案(而且很容易实现!)。
The following code is called as part of -viewDidLoad
in my UIViewController
.
以下代码-viewDidLoad
在我的UIViewController
.
// My app is restricted to portrait-only, so the following works
UIToolbar *numberPadAccessoryInputView = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 44.0f)];
// My app-wide tint color is a gold-ish color, so darkGray contrasts nicely
numberPadAccessoryInputView.barTintColor = [UIColor darkGrayColor];
// A basic "Done" button, that calls [self.textField resignFirstResponder]
UIBarButtonItem *numberPadDoneButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self.textField action:@selector(resignFirstResponder)];
// It's the only item in the UIToolbar's items array
numberPadAccessoryInputView.items = @[numberPadDoneButton];
// In case the background of the view is similar to [UIColor darkGrayColor], this
// is put as a contrasting edge line at the top of the UIToolbar
UIView *topBorderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, numberPadAccessoryInputView.frame.size.width, 1.0f)];
topBorderView.backgroundColor = [UIColor whiteColor];
[numberPadAccessoryInputView addSubview:topBorderView];
// Make it so that this UITextField shows the UIToolbar
self.textField.inputAccessoryView = numberPadAccessoryInputView;
With that, there's a nice, pretty, intuitive control added to the top of the keyboard that clearly indicates how the user should proceed when they are finished with their text entry.
有了它,键盘顶部添加了一个漂亮、漂亮、直观的控件,可以清楚地指示用户在完成文本输入后应该如何继续。
I still believe Apple should provide a "Done" button for this keyboard (like the link posted by Janak Nirmal), but this is the most elegant non-Apple solution to me.
我仍然相信 Apple 应该为这个键盘提供一个“完成”按钮(就像 Janak Nirmal 发布的链接),但这对我来说是最优雅的非 Apple 解决方案。
回答by SimplGy
You can implement @mbm's answer really nicely by putting a didSet
on the outlet and attaching your inputAccessoryView there:
您可以通过didSet
在插座上放置一个并将您的 inputAccessoryView 附加到那里来很好地实现@mbm 的答案:
Swift code:
SWIFT代码:
@IBOutlet var input: UITextField! { didSet {
let toolbar = UIToolbar(frame: CGRect(origin: CGPoint.zero, size: CGSize(width: 0, height: 44)))
toolbar.items = [
UIBarButtonItem(barButtonSystemItem: .done, target: self.input,
action: #selector(resignFirstResponder))
]
input.inputAccessoryView = toolbar
}}
In xcode 8 / iOS 10 It ends up looking something like this:
在 xcode 8 / iOS 10 中,它最终看起来像这样:
回答by Vignesh
You must use UITapGestureRecognizer to achieve this.
您必须使用 UITapGestureRecognizer 来实现这一点。
UITapGestureRecognizer *tapToDismiss = [[UITapGestureRecognizer alloc]initWithTarget: self action: @selector (dismissNumberKeyBoard:)];
Then in your dismissNumberKeyboard method,
然后在你的dismissNumberKeyboard 方法中,
-(Void)dismissNumberKeyboard : (id)sender {
[yourTextField resignFirstResponder];
}
Happy coding!
快乐编码!
回答by Oleksii Radetskyi
For swift 3/4 I like this case:
对于 swift 3/4 我喜欢这个案例:
- View Controller is subclass for UITextFieldDelegate
- In the viewDidLoad function, you have to set
yourPhonePadField.delegate = self
And override this function:
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { self.view.endEditing(true) }
- 视图控制器是 UITextFieldDelegate 的子类
- 在 viewDidLoad 函数中,你必须设置
yourPhonePadField.delegate = self
并覆盖此功能:
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { self.view.endEditing(true) }
回答by Hadi
Just make a simple function like this one..
只需做一个像这样的简单功能..
-(IBAction)hideKeyboard:(id)Sender
{
[_textValue resignFirstResponder];
}
now go to ur nib file and connect this function with the textfield with didEndOnExit
and you are good to go. Now when u will click outside ur textfield the keyboard will hide itself.
现在转到您的 nib 文件并将此功能与文本字段连接起来didEndOnExit
,您就可以开始了。现在,当您在文本字段外单击时,键盘将隐藏自身。
回答by Srikar Appalaraju
Normally, when the user touches on 'Cancel' button, I use this to dismiss Keyboard -
通常,当用户触摸“取消”按钮时,我会使用它来关闭键盘 -
- (void)searchBarCancelButtonClicked:(UISearchBar *) searchBar
{
NSLog(@"cancel clicked");
[searchBar resignFirstResponder]; // dismiss keyboard
return;
}
If you want to do this for when the user touches anywhere outside the keyboard area, then you need to implement touchesEnded
& put this code there -
如果您想在用户触摸键盘区域外的任何地方时执行此操作,那么您需要实现touchesEnded
并将此代码放在那里 -
/* Delegate for when touch ends. */
-(void)touchesEnded:(NSSet *)touches
withEvent:(UIEvent *)event
{
[searchBar resignFirstResponder];
}
I myself have not tried this, but I recon this should do the trick...
我自己没有尝试过这个,但我认为这应该可以解决问题......