UITextFieldをタップしたときにキーボードの下に隠れないようにする
This file contains 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]; | |
// キーボード表示・非表示時のイベント登録 | |
[[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