Unable to scroll? What's wrong with my code?
This is my code as follows:
-(void) viewWillAppear:(BOOL)animated {
开发者_StackOverflow [super viewWillAppear:YES];
NSLog(@"------>> Reigster for keyboard events");
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardDidShow:)
name:UIKeyboardDidShowNotification
object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardDidHide:)
name:UIKeyboardDidHideNotification
object:nil];
keyboardVisible = NO;
}
-(void) viewWillDisappear:(BOOL)animated {
NSLog(@"--->>Unregister keyboard event");
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
-(void)keyboardDidShow:(NSNotification *) notif{
NSLog(@"Received did show notifiation");
if (keyboardVisible) {
NSLog(@"Keyboard is already visible... ignoring notification");
return;
}
NSLog(@"Resizing smaller for keboard");
NSDictionary *info = [notif userInfo];
NSValue *aValue = [info objectForKey:UIKeyboardFrameBeginUserInfoKey];
CGSize keyboardSize = [aValue CGRectValue].size;
CGRect viewFrame = self.view.frame;
viewFrame.size.height -= keyboardSize.height;
scrollView.frame = viewFrame;
scrollView.contentSize = CGSizeMake(viewFrame.size.width, viewFrame.size.height);
//scrollView.contentSize = CGSizeMake(296, 217);
keyboardVisible = YES;
}
-(void) keyboardDidHide:(NSNotification *) notif {
NSLog(@"Received did Hide notification");
if (!keyboardVisible) {
NSLog(@"keyboard already hidden. Ignoring notification");
return;
}
NSLog(@"Resizing bigger with no keyboard");
NSDictionary *info = [notif userInfo];
NSValue *aValue = [info objectForKey:UIKeyboardFrameBeginUserInfoKey];
CGSize keyboardSize = [aValue CGRectValue].size;
CGRect viewFrame = self.view.frame;
viewFrame.size.height += keyboardSize.height;
//scrollView.contentSize = CGSizeMake(296, 417);
scrollView.contentSize = CGSizeMake(viewFrame.size.width, viewFrame.size.height);
keyboardVisible = NO;
}
The same question was discussed earlier, I would like you to go to this SO question and find out by yourself what is missing.
There are two issues. First, you should use UIKeyboardFrameEndUserInfoKey
instead of UIKeyboardFrameBeginUserInfoKey
.
Second, you really should use the origin of the keyboard after converting it to your view's local coordinate space. Just using the returned frame without using -[UIView convertRect:fromView:] won't work if the device is in landscape or your view's coordinates are different from the window's coordinates. You should use the origin of the transformed coordinates instead of the height since the height might refer to a part of the keyboard that is off screen. This happens, for example, when using a bluetooth keyboard.
精彩评论