従って、Text Viewを使ってテキストを入力させているときは、全領域を見えるようにするためにText Viewの枠を調整する必要がある。
1. キーボード表示の通知を登録する
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
// 通知の受け取りを登録する
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardWillShow:)
name:UIKeyboardWillShowNotification
object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardWillHide:)
name:UIKeyboardWillHideNotification
object:nil];
}
2. キーボード通知の登録を解除する
- (void)viewWillDisappear:(BOOL)animated {
[super viewWillDisappear:animated];
// 通知の受け取りを登録解除する
[[NSNotificationCenter defaultCenter] removeObserver:self
name:UIKeyboardWillShowNotification
object:nil];
[[NSNotificationCenter defaultCenter] removeObserver:self
}
3. キーボードを表示するときに、Text Viewの枠を調整する
- (void)keyboardWillShow:(NSNotification*)aNotification {
NSDictionary* info = [aNotification userInfo];
CGRect kbSize = [[info objectForKey:UIKeyboardFrameEndUserInfoKey]
CGRectValue];
double duration = [[info
objectForKey:UIKeyboardAnimationDurationUserInfoKey]
doubleValue];
UIEdgeInsets insets = self.textView.contentInset;
insets.bottom += kbSize.size.height;
[UIView animateWithDuration:duration animations:^{
self.textView.contentInset = insets;
}];
}
4. キーボードを閉じるときに、Text Viewの枠を元に戻す
- (void)keyboardWillHide:(NSNotification*)aNotification {
NSDictionary* info = [aNotification userInfo];
double duration = [[info
objectForKey:UIKeyboardAnimationDurationUserInfoKey]
doubleValue];
// Text Viewの下部コンテンツ挿入枠をリセットする
UIEdgeInsets insets = self.textView.contentInset;
insets.bottom = 0;
[UIView animateWithDuration:duration animations:^{
self.textView.contentInset = insets;
}];
}
参考記事:
https://developer.apple.com/jp/devcenter/ios/library/documentation/iCloud101.pdf
【キーボードの最新記事】