Last active
December 21, 2015 10:09
-
-
Save Ridwy/6290416 to your computer and use it in GitHub Desktop.
UITextFieldがキーボードで隠れないようにスクロールアップする方法。
ViewControllerに以下のコードを実装してUITextFieldのdelegateにする
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
- (void)viewWillAppear:(BOOL)animated | |
{ | |
[super viewWillAppear:animated]; | |
// register for keyboard notifications | |
[[NSNotificationCenter defaultCenter] addObserver:self | |
selector:@selector(keyboardWillHide) | |
name:UIKeyboardWillHideNotification | |
object:nil]; | |
} | |
- (void)viewWillDisappear:(BOOL)animated | |
{ | |
[super viewWillDisappear:animated]; | |
// unregister for keyboard notifications while not visible. | |
[[NSNotificationCenter defaultCenter] removeObserver:self | |
name:UIKeyboardWillHideNotification | |
object:nil]; | |
} | |
#pragma mark - scroll up when keyboard is present | |
-(void)textFieldDidBeginEditing:(UITextField *)sender | |
{ | |
// Animate the current view out of the way | |
CGPoint p = [self.view.superview convertPoint:sender.frame.origin fromView:self.view]; | |
if (self.view.superview.bounds.size.height - p.y < 280) { | |
offsetForKeyboard = p.y - 100; // offsetForKeyboardはivar | |
CGRect r = self.view.frame; | |
r.origin.y -= offsetForKeyboard; | |
r.size.height = self.view.superview.bounds.size.height + offsetForKeyboard; | |
[UIView animateWithDuration:0.3 animations:^{ | |
self.view.frame = r; | |
}]; | |
} | |
} | |
-(void)keyboardWillHide | |
{ | |
if (0 < offsetForKeyboard) { | |
offsetForKeyboard = 0; | |
[UIView animateWithDuration:0.3 animations:^{ | |
self.view.frame = self.view.superview.bounds; | |
}]; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment