IOS – 如果用户点击randome元素而不是背景,如何隐藏键盘?

在我的应用程序中,我有这样的事情:

- (IBAction)backgroundTouch:(id)sender { [businessDescription resignFirstResponder]; [self.view endEditing:YES]; } 

我不确定我使用的两条线中的哪一条更好,所以我同时使用它们:)当文本区域突出显示时,用户按下背景。

但是用户并不总是按下背景,有时会按下其他页面元素,例如他们试图填写的下一个元素。

在我的屏幕截图中,我在文本区域下面有下一个元素,当我点击那里时,键盘不会被隐藏。 当用户点击各种页面元素时,以及当textarea没有突出显示时,有人可以帮我隐藏键盘吗?

在此处输入图像描述

这是我的.h文件:

 @interface PlanBusinessController : UIViewController @property (weak, nonatomic) IBOutlet UITextView *businessDescription; - (IBAction)submitBusiness:(id)sender; @property (weak, nonatomic) IBOutlet UIButton *buttonProperty; @property (weak, nonatomic) IBOutlet UITextField *personName; @property (weak, nonatomic) IBOutlet UITextField *personEmail; @property (weak, nonatomic) IBOutlet UISwitch *privacy; @property (weak, nonatomic) IBOutlet UISwitch *wantHelp; - (IBAction)helpToggle:(id)sender; @property (weak, nonatomic) IBOutlet UILabel *nameLabel; @property (weak, nonatomic) IBOutlet UILabel *emailLabel; @property (weak, nonatomic) IBOutlet UIButton *test; 

@结束

这是我的.m声明:

 #import "PlanBusinessController.h" @interface PlanBusinessController () @end @implementation PlanBusinessController @synthesize nameLabel; @synthesize emailLabel; @synthesize businessDescription; @synthesize buttonProperty; @synthesize personName; @synthesize personEmail; @synthesize privacy; @synthesize wantHelp; @synthesize test; -(void)touchesBegan:(NSSet*)touches { UITouch *touch=[touches anyObject]; UIView *view=touch.view; if (![view isEqual:businessDescription]) { //[businessDescription resignFirstReponder]; } } - (IBAction)backgroundTouch:(id)sender { [businessDescription resignFirstResponder]; [self.view endEditing:YES]; } 

谢谢!

我在我的程序ViewController中使用此方法,它工作正常。 我试一试。

 //Used with the text fields to dismiss keyboard - (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event { [textField resignFirstResponder]; } 

如果您有其他元素,那么在这些元素的方法中也添加[textField resignFirstResponder]

例如,如果他们可以点击按钮,请写下这样的内容:

 -(IBAction)button1:(id)sender { [textField resignFirstResponder]; //Do stuff } 

注意:您要关闭的每个文本字段都需要一个。 例如:

 -(IBAction)button1:(id)sender { [textField resignFirstResponder]; [textField2 resignFirstResponder]; []... etc //Do stuff } 

请检查以下代码:

 -(void)touchesBegan:(NSSet*)touches { UITouch *touch = [touches anyObject]; UIView *textView=touch.view; if (![textView isKindOfClass:[UITextView class]]) { [businessDescription resignFirstResponder]; } } 

当你触摸一个对象时,它会检查,触摸的对象是否是一种UITextView ,如果没有它将结束编辑。

一种简单的方法是捕捉触摸发生的视图。 并将其与文本区域进行比较。 如果视图或(其他类似按钮)与文本区域不同,则可以隐藏键盘。 这是伪代码:

  -(void)touchesBegan:(NSSet*)touches { UITouch *touch=[touches anyObject]; UIView *view=touch.view; if (![view isEqual:textArea]) [textarea resignFirstReponder]; }