Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Moving view up to accommodate keyboard

I have a view with multiple text fields and I want to do the same effect that the Contacts application does when you click on a text field would otherwise be hidden by the keyboard when it comes up. When I dismiss the keyboard I plan on moving the view back down properly.

I suspect that I do this by changing the Frame value, but I need this to be animated so that it isn't jarring to the user.

Advice? Examples?

like image 373
Driss Zouak Avatar asked Jan 20 '23 08:01

Driss Zouak


2 Answers

Wrapping your view in a UIScrollView is indeed the way to go. As well as on the textFieldDidEndEditing delegate, you could instead subscribe to the UIKeyboardDidHideNotification and UIKeyboardDidShowNotification and when you receive a notification that the keyboard did hide/show then scroll your view appropriately. I can post code examples for the keyboard notifications if you need it : )

Edit Figured I'd post the code anyway - someone might find it helpful:

You need to declare listeners for the notifications:

NSObject hideObj = NSNotificationCenter.DefaultCenter.AddObserver(UIKeyboard.DidHideNotification, HandleKeyboardDidHide);
NSObject showObj = NSNotificationCenter.DefaultCenter.AddObserver(UIKeyboard.DidShowNotification, HandleKeyboardDidShow);   

then your Action methods would look something like:

void HandleKeyboardDidShow(NSNotification notification)
{
     scrollView.ScrollRectToVisible(textfield.Frame, true);
}

void HandleKeyboardDidHide(NSNotification notification)
{
     // scroll back to normal
}

Edit 2

So if you'd like to remove the Observers when the view is destroyed, first you need to ensure you assign NSObjects when adding the observers then use the following code to remove them:

NSNotificationCenter.DefaultCenter.RemoveObserver(showObj);
NSNotificationCenter.DefaultCenter.RemoveObserver(hideObj);

Hope that helps.

like image 129
Luke Avatar answered Jan 27 '23 21:01

Luke


I just did this on an application. I used a scrollview to wrap my entire view, and then used scrollToRectVisible on the textFieldDidEndEditing-delegate method. It worked perfectly!

like image 38
Jensen2k Avatar answered Jan 27 '23 21:01

Jensen2k