IOS virtual keyboard size without notification center

I need to scroll my scrollView when textFiewl is being listened, which is below the virtual keyboard. I call [self.scrollView setContentOffset:scrollPoint animated:YES]; . To get the visible area of ​​the screen, I obviously need a KB size.

I am familiar with

 NSDictionary *info = [notification userInfo]; CGSize kbSize = [self.view convertRect: [info[UIKeyboardFrameBeginUserInfoKey] CGRectValue] fromView:nil].size; 

however, this does not work for me, because when a user types a possibly half-covered text field, I do not receive keyboard notifications.

So, I call the method in textFieldDidBeginEditing: which is called before the keyboard sends a message, and therefore I do not know the KB size on the first press.

So, the question arises: is it possible to get the size of the KB without calling the corresponding notification? Programmatically, not hardcoding.

+4
source share
1 answer

You are doing it wrong.

You also need to listen to the show / hide notifications on the keyboard, and then adjust the screen.

Here is an example of skeletal code:

 - (void)viewWillAppear:(BOOL)animated { [super viewWillAppear:animated]; NSNotificationCenter *nc = [NSNotificationCenter defaultCenter]; [nc addObserver:self selector:@selector(keyboardChangedStatus:) name:UIKeyboardWillShowNotification object:nil]; [nc addObserver:self selector:@selector(keyboardChangedStatus:) name:UIKeyboardWillHideNotification object:nil]; } - (void)viewWillDisappear:(BOOL)animated { [super viewWillDisappear:animated]; NSNotificationCenter *nc = [NSNotificationCenter defaultCenter]; [nc removeObserver:self name:UIKeyboardWillShowNotification object:nil]; [nc removeObserver:self name:UIKeyboardWillHideNotification object:nil]; } #pragma mark - Get Keyboard size - (void)keyboardChangedStatus:(NSNotification*)notification { //get the size! CGRect keyboardRect; [[[notification userInfo] objectForKey:UIKeyboardFrameEndUserInfoKey] getValue:&keyboardRect]; keyboardHeight = keyboardRect.size.height; //move your view to the top, to display the textfield.. [self moveView:notification keyboardHeight:keyboardHeight]; } #pragma mark View Moving - (void)moveView:(NSNotification *) notification keyboardHeight:(int)height{ [UIView beginAnimations:nil context:NULL]; [UIView setAnimationDuration:0.3]; [UIView setAnimationBeginsFromCurrentState:YES]; CGRect rect = self.view.frame; if ([[notification name] isEqual:UIKeyboardWillHideNotification]) { // revert back to the normal state. rect.origin.y = 0; hasScrolledToTop = YES; } else { // 1. move the view origin up so that the text field that will be hidden come above the keyboard (you need to adjust the value here) rect.origin.y = -height; } self.view.frame = rect; [UIView commitAnimations]; } 
+3
source

All Articles