Skip to content

Instantly share code, notes, and snippets.

@setoh2000
Last active August 29, 2015 14:19
Show Gist options
  • Save setoh2000/c8b62654c6e9dccc9c43 to your computer and use it in GitHub Desktop.
Save setoh2000/c8b62654c6e9dccc9c43 to your computer and use it in GitHub Desktop.
Autolayoutでキーボードの高さによってViewを調整する方法(Objective-C版)
// ↓ここで紹介されていたSwiftのコードをObjective-Cに置き換えたものです。
//
// Autolayoutでキーボードの高さによってViewを調整する方法
// http://blog.tsumikiinc.com/article/20150123_autolayout-view.html
//
// StoryboardでUITextViewのBottomのVertical Space ConstraintとbottomLayoutConstraintを接続する必要があります。
// 詳細は元のBlog記事を参照ください。
@property (nonatomic, weak) IBOutlet NSLayoutConstraint *bottomLayoutConstraint;
// 〜
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillChangeFrame:) name:UIKeyboardWillChangeFrameNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
}
- (void)viewWillDisappear:(BOOL)animated
{
[super viewWillDisappear:animated];
[[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillChangeFrameNotification object:nil];
[[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
}
- (void)keyboardWillChangeFrame:(NSNotification *)aNotification
{
CGRect keyBoardFrame = [[[aNotification userInfo] objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
NSTimeInterval duration = [[[aNotification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
self.bottomLayoutConstraint.constant = keyBoardFrame.size.height;
[UIView animateWithDuration:duration animations:^{
[self.view layoutIfNeeded];
}];
}
- (void)keyboardWillHide:(NSNotification *)aNotification
{
NSTimeInterval duration = [[[aNotification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
self.bottomLayoutConstraint.constant = 0;
[UIView animateWithDuration:duration animations:^{
[self.view layoutIfNeeded];
}];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment