添加监听
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardAction:) name:UIKeyboardWillShowNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardAction:) name:UIKeyboardWillShowNotification object:nil];
键盘监听事件
// 键盘监听事件
-(void)keyboardAction:(NSNotification *)sender{
NSDictionary *userInfo = [sender userInfo];
NSValue *value = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
// 通过通知对象获取键盘frame: [value CGRectValue]
CGFloat keyboardHeight = [value CGRectValue].size.height;
CGFloat bottomHeight = self.Height - self.backgroundView.Bottom - 15;
if (bottomHeight <= keyboardHeight) {
[UIView animateWithDuration:0.2 animations:^{
self.backgroundView.Top = self.backgroundView.Top - keyboardHeight + bottomHeight;
}];
}
}
可能用到的其他方法
// 点击非TextField区域取消第一响应者
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
[self.inputField resignFirstResponder];
}
// 点击键盘Return键取消第一响应者
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
[self.inputField resignFirstResponder];
return YES;
}
// 点击按钮取,消第一响应者
- (IBAction)okAction:(UIButton *)sender {
[self.inputField resignFirstResponder];
}