Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.