// return回收键盘
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
[textField resignFirstResponder];
return YES;
}
// 点击空白处回收键盘
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
[self.textField resignFirstResponder];
}
// 动态监听键盘高度(在viewDidLoad里直接调用registerForKeyboardNotifications方法就行了)
- (void)registerForKeyboardNotifications
{
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWasShown:) name:UIKeyboardDidShowNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWasHidden:) name:UIKeyboardDidHideNotification object:nil];
}
- (void)keyboardWasShown:(NSNotification *)notification
{
NSDictionary *info = [notification userInfo];
NSValue *value = [info objectForKey:UIKeyboardFrameBeginUserInfoKey];
CGSize keyboardSize = [value CGRectValue].size;
CGFloat bottomHeight = kHeight - CGRectGetMaxY(self.textField.frame);
CGFloat keyboardHeight = keyboardSize.height + k6AutoSize(40);
if (bottomHeight.floatValue < keyboardHeight) {
[UIView animateWithDuration:0.5 animations:^{
self.view.frame = CGRectMake(0, bottomHeight - keyboardHeight, kWidth, kHeight);
}];
} else {
[UIView animateWithDuration:0.5 animations:^{
self.view.frame = CGRectMake(0, 0, kWidth, kHeight);
}];
}
}
- (void)keyboardWasHidden:(NSNotification *)notification
{
[UIView animateWithDuration:0.5 animations:^{
self.view.frame = CGRectMake(0, 0, kWidth, kHeight);
}];
}
注意:如果有多个TextField
/**
* 获取正在编辑的textField
*
* @param textField 正在编辑的textField
*/
- (void)textFieldDidBeginEditing:(UITextField *)textField
{
self.textField = textField;
}