代码如下:
//增加监听,当键盘出现或改变时收出消息
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardWillShow:)
name:UIKeyboardWillShowNotification
object:nil];
//增加监听,当键退出时收出消息
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardWillHide:)
name:UIKeyboardWillHideNotification
object:nil];
//当键盘出现或改变时调用
- (void)keyboardWillShow:(NSNotification *)aNotification
{
//获取键盘的高度
NSDictionary *userInfo = [aNotification userInfo];
NSValue *aValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
CGRect keyboardRect = [aValue CGRectValue];
int height = keyboardRect.size.height;
[UIView animateWithDuration:1 animations:^{
if (kSCREENWIDTH < 375)
{
if (kSCREENHEIGHT <= 480)
{
self.view.frame = CGRectMake(0, self.view.frame.origin.y - height/2, kSCREENWIDTH, kSCREENHEIGHT);
}
else
{
self.view.frame = CGRectMake(0, self.view.frame.origin.y - height/2, kSCREENWIDTH, kSCREENHEIGHT);
}
}
}];
}
//当键退出时调用
- (void)keyboardWillHide:(NSNotification *)aNotification
{
//获取键盘的高度
NSDictionary *userInfo = [aNotification userInfo];
NSValue *aValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
CGRect keyboardRect = [aValue CGRectValue];
int height = keyboardRect.size.height;
[UIView animateWithDuration:1 animations:^{
if (kSCREENWIDTH < 375)
{
if (kSCREENHEIGHT <= 480)
{
self.view.frame = CGRectMake(0, self.view.frame.origin.y + height/2, kSCREENWIDTH, kSCREENHEIGHT);
}
else
{
self.view.frame = CGRectMake(0, self.view.frame.origin.y + height/2, kSCREENWIDTH, kSCREENHEIGHT);
}
}
}];
}