- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
_textfield = [[UITextField alloc]initWithFrame:CGRectMake(10, 460-100-26, 300-34, 26)];
_textfield.borderStyle = UITextBorderStyleRoundedRect;
_textfield.tag = 444;
_textfield.delegate = self;
[_textfield addTarget:self action:@selector(keyboardWillShow:) forControlEvents:UIControlEventTouchDown];
[self.view addSubview:_textfield];
}
-(void)keyboardWillShow:(UITextField*)textfield
{
//在iOS5中,新增有notification(UIKeyboardWillChangeFrameNotification)可以用来监测键盘frame的变化。在iOS4中,可以通过UIKeyboardWillShowNotification以及UIKeyboardWillHideNotification来监测键盘的显示与隐藏事件
/*****************/
// 该notification由系统发送,所以无需自己调用发送通知
/*****************/
/* 通知描述:
UIKeyboardWillShowNotification键盘即将显示
UIKeyboardDidShowNotification键盘已经显示
UIKeyboardWillHideNotification键盘即将隐藏
UIKeyboardDidHideNotification键盘已经隐藏
UIKeyboardWillChangeFrameNotification键盘frame即将改变
UIKeyboardDidChangeFrameNotification键盘frame已经改变
*/
//注册监测事件
if (IOS_VERSION < 5.0) {
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillChangeFrame:) name:UIKeyboardWillShowNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillChangeFrame:) name:UIKeyboardWillHideNotification object:nil];
}else{
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillChangeFrame:) name:UIKeyboardWillChangeFrameNotification object:nil];
}
}
- (void)keyboardWillChangeFrame:(NSNotification *)notification
{
//获取键盘信息
NSDictionary *info=[notification userInfo];
NSLog(@"info = %@",info);
//获取键盘的size值
CGSize _keyBord = [[info objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size;
//获取键盘出现的动画时间
NSValue *animationDurationValue = [info objectForKey:UIKeyboardAnimationDurationUserInfoKey];
NSTimeInterval animationDuration;
[animationDurationValue getValue:&animationDuration];
//获取键盘高度
CGFloat height = _keyBord.height;
NSLog(@"hhh = %f",height);
NSTimeInterval animation = animationDuration;
//视图移动的动画开始
[UIView beginAnimations:@"animal" context:nil];
[UIView setAnimationDuration:animation];
[_textfield setFrame:CGRectMake(10, 460-height-26, 300-24, 26)];
[UIView commitAnimations];
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
//移除监测事件
[[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillChangeFrameNotification object:nil];
NSTimeInterval animationDuration = 0.30f;
[UIView beginAnimations:@"ResizeForKeyboard" context:nil];
[UIView setAnimationDuration:animationDuration];
[_textfield setFrame:CGRectMake(10, 460-100-26, 300-34, 26)];
[UIView commitAnimations];
[textField resignFirstResponder];
// textfield.text = nil;
return YES;
}