LoginSignup
1
1

More than 5 years have passed since last update.

Automatically Change UIView's Frame In Relation to the Keyboard

Last updated at Posted at 2013-12-06

This would be my first post on Qiita :), since Japanese is not my first language, I am going to start with an English post and work my way to writing Japanese posts. This post shows you how to change the frame of your view when the keyboard frame changes. Certain UI design puts elements right above the edge of the keyboard (see below), and that's where this technique comes in handy.
iOS Simulator Screen shot Dec 6, 2013, 1.30.06 PM.png

When you start typing in language which uses Kanji, like Japanese or Chinese, the keyboard will provide suggested combinations of words, which may cause overlaying views like this:
iOS Simulator Screen shot Dec 6, 2013, 1.30.10 PM.png

When this happens, you can use UIKeyboardWillChangeFrameNotification to move up your views and avoid your UI to be covered by the keyboard, and adding a small bouncy animation would not hurt. This will also ensure that whatever you placed right above the keyboard stays where it should be when the user is typing in any other language.
iOS Simulator Screen shot Dec 6, 2013, 1.31.15 PM.png

Let's code!

Firstly, add a NSNotificationCenter to detect the change of keyboard frame:

[[NSNotificationCenter defaultCenter] addObserver:self 
                  selector:@selector(keyboardWillChangeFrame:) 
                   name:UIKeyboardWillChangeFrameNotification object:nil];

Then implement the keyboardWillChangeFrame: method as the following:

-(void)keyboardWillChangeFrame:(NSNotification *)notification{
    
    NSValue *frameValue = notification.userInfo[UIKeyboardFrameEndUserInfoKey];
    CGRect frame = [frameValue CGRectValue];
    
    frame = [self.view convertRect:frame fromView:nil];
    CGFloat originY = frame.origin.y - 80;
    self.layoutView.frame = CGRectMake(0, originY, 320, 80);
    CGFloat textviewHeight = self.view.bounds.size.height - frame.size.height - 80;
    self.textView.frame = CGRectMake(0, 0, 320, textviewHeight);
    
}

The notification.userInfo[UIKeyboardFrameEndUserInfoKey] will return an instance of NSValue which contains information about the keyboard's frame. Therefore all you need to do it to set your view's position in relation to this information. that's all you need to do :)

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1