标签:
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
[_tfPassword resignFirstResponder];
[_tfUsername resignFirstResponder];
}
#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
标签:
原文地址:http://www.cnblogs.com/dongfangchun/p/5340553.html