Search code examples
iosxcodeuipickerviewnsnotificationcenter

How to move view up when a UIPickerView is displayed


I have a mainview with all of my textfields and buttons. For my textfields i am using the inputView to display UIPickerViews instead of the keyboards. I am wondering how I can main the view move up when a textfield is selected that way the picker and the pickers toolbar does not cover up the textfield, because i have some textfields at the bottom that get covered by it. I have tried using the following code from a tutorial with a table view, but it does not work for me. It builds without error, but it does not work right. The view just disappears and then it only comes back down half way when the pickerView is dismissed.

    - (void)viewDidLoad {
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(pickerShown:) name:UIKeyboardDidShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(pickerHidden:) name:UIKeyboardWillHideNotification object:nil];

}

-(void)pickerShown:(NSNotification *)note {
CGRect pickerFrame;
[[[note userInfo] objectForKey:UIKeyboardFrameEndUserInfoKey]   getValue:&pickerFrame];
CGRect scrollViewFrame = mainView.frame;
scrollViewFrame.size.height -= pickerFrame.size.height;
[mainView setFrame:pickerFrame];
}
-(void)pickerHidden:(NSNotification*)note{
[mainView setFrame:self.view.bounds];
}

Is this close to what i need to be doing?


Solution

  • May I suggest having a look at this tutorial "Sliding UITextFields around to avoid the keyboard".

    In your case, you need to put the code they have in textFieldDidBeginEditing in your pickerShown method, and change the constants that they have for keyboard heights for the picker heights instead.

    Hope this helps :)