Skip to content

Instantly share code, notes, and snippets.

  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save hisasann/3213917 to your computer and use it in GitHub Desktop.
UITextFieldをタップしたときにキーボードの下に隠れないようにする
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
// キーボード表示・非表示時のイベント登録
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardWasShown:)
name:UIKeyboardDidShowNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardWasHidden:)
name:UIKeyboardDidHideNotification object:nil];
}
- (void)viewWillDisappear:(BOOL)animated {
// キーボード表示・非表示時のイベント削除
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
- (void)keyboardWasShown:(NSNotification *)notification {
NSDictionary *info = [notification userInfo];
CGSize kbSize = [[info objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;
UIEdgeInsets contentInsets = UIEdgeInsetsMake(0.0, 0.0, kbSize.height, 0.0);
self.scrollView.contentInset = contentInsets;
self.scrollView.scrollIndicatorInsets = contentInsets;
CGRect aRect = self.view.frame;
aRect.size.height -= kbSize.height;
if (_activeField != nil) {
CGPoint scrollPoint = CGPointMake(0.0, _activeField.frame.origin.y - 30);
[self.scrollView setContentOffset:scrollPoint animated:YES];
}
}
- (void)keyboardWasHidden:(NSNotification *)notification {
UIEdgeInsets contentInsets = UIEdgeInsetsZero;
self.scrollView.contentInset = contentInsets;
self.scrollView.scrollIndicatorInsets = contentInsets;
}
- (void)textFieldDidBeginEditing:(UITextField *)textField {
_activeField = textField;
}
- (void)textFieldDidEndEditing:(UITextField *)textField {
_activeField = nil;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment