方法1. 使用<UITextFeildDelegate>,使用的UITextField示例 设置其Delegate为self,点击return按钮隐藏键盘。实现函数如下:
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
[textField resignFirstResponder];
return YES;
}
方法2. 点击界面的其它空白地方隐藏
由于UIViewController是继承自UIResponder的,所以可以覆写- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event;这个开始触摸的方法来取消第一响应者,代码如下:
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
[_tfPassword resignFirstResponder];
[_tfUsername resignFirstResponder];
}
以上两种方法是初学iOS的时候使用的。
3. 最好还是使用NotificationCenter的方法比较好,能获取键盘高度等详细信息
#import "ViewController.h" @interface ViewController () @property (weak, nonatomic) IBOutlet UITextField *tfTest; @property (weak, nonatomic) IBOutlet UITextField *tfTest2; @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; } - (void)viewDidappear:(BOOL)animated { [super viewDidDisappear:animated]; //移除键盘监听消息 [[NSNotificationCenter defaultCenter]removeObserver:self name:UIKeyboardWillShowNotificationobject:nil]; [[NSNotificationCenter defaultCenter]removeObserver:self name:UIKeyboardWillHideNotificationobject:nil]; //注册键盘监听消息 [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyShow:)name:UIKeyboardWillShowNotification object:nil]; [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyHide:)name:UIKeyboardWillHideNotification object:nil]; } //弹出键盘消息响应 - (void)keyShow:(NSNotification *)no { NSLog(@"keyShow"); NSDictionary *dic = [no valueForKey:@"userInfo"]; CGFloat heightKeyboard = [[dicvalueForKey:@"UIKeyboardBoundsUserInfoKey"]CGRectValue].size.height; UIView *firstResponderView = [self getFirstResponderView]; CGFloat distanceToBottom = self.view.frame.size.height -CGRectGetMaxY(firstResponderView.frame); //动画 if(distanceToBottom < heightKeyboard){ CGRect frame = self.view.frame; frame.origin.y = -(heightKeyboard - distanceToBottom); [UIView animateWithDuration:0.3f animations:^{ [self.view setFrame:frame]; } completion:^(BOOL finished) { }]; } } //关闭键盘消息响应 - (void)keyHide:(NSNotification *)no { NSLog(@"keyHide"); CGRect frame = self.view.frame; frame.origin.y = 0; //动画 [UIView animateWithDuration:0.3f animations:^{ [self.view setFrame:frame]; } completion:^(BOOL finished) { }]; } //点击背景区域自动隐藏键盘 - (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event { UIView *firstResponderView = [self getFirstResponderView]; [firstResponderView resignFirstResponder]; } //获取当前焦点所在的控件 - (UIView *)getFirstResponderView{ UIWindow *keyWindow = [[UIApplication sharedApplication]keyWindow]; UIView *firstResponder = [keyWindow performSelector:@selector(firstResponder)]; return firstResponder; } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; } @end
时间: 2024-11-05 18:32:22