我试图获得iOS键盘的高度,以便在键盘动画时我可以移动我的视图。但是,我一直得到返回值258(这是不正确的,因为它推动我的视图太高了?)为什么会发生这种情况?代码如下:
ViewController.m
-(void)viewDidLoad {
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillChange:) name:UIKeyboardWillChangeFrameNotification object:nil];
}
- (void)keyboardWillChange:(NSNotification *)notification {
NSDictionary* keyboardInfo = [notification userInfo];
NSValue* keyboardFrameBegin = [keyboardInfo valueForKey:UIKeyboardFrameEndUserInfoKey];
CGRect keyboardFrameBeginRect = [keyboardFrameBegin CGRectValue];
self.keyboardHeight = keyboardFrameBeginRect.size.height;
}
- (void) animateTextView:(BOOL) up
{
const int movementDistance = self.keyboardHeight;
const float movementDuration = 0.3f;
int movement= movement = (up ? -movementDistance : movementDistance);
[UIView beginAnimations: @"anim" context: nil];
[UIView setAnimationBeginsFromCurrentState: YES];
[UIView setAnimationDuration: movementDuration];
self.upView.frame = CGRectOffset(self.upView.frame, 0, movement);
[UIView setAnimationDidStopSelector:@selector(afterAnimationStops)];
[UIView commitAnimations];
}
答案 0 :(得分:1)
要获得键盘高度,您应使用UIKeyboardWillShowNotification
或UIKeyboardDidShowNotification
代替UIKeyboardWillChangeFrameNotification.
-(void)viewDidLoad {
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillChange:) name:UIKeyboardWillShowNotification object:nil];
}
如果使用UITabBarController
,则必须在没有标签栏高度的情况下计算框架。您可以使用下面的代码获得标签栏高度。
self.tabBarController.tabBar.frame.height
答案 1 :(得分:0)
您应该注册UIKeyboardWillShowNotification以观察键盘高度。
1) [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillChange:) name:UIKeyboardWillShowNotification object:nil];
2)你也可以试试这段代码:
(void)keyboardWillChange:(NSNotification *)notification
{
NSDictionary* keyboardInfo = [notification userInfo];
NSValue* keyboardFrameBegin = [keyboardInfo valueForKey:UIKeyboardFrameBeginUserInfoKey];
CGRect keyboardFrameBeginRect = [keyboardFrameBegin CGRectValue];
}