アプリにキーボードが表示されたときにビューを上にスライドできるので、テキストフィールドが表示され、問題なく機能しました。ただし、キーボード通知に基づいているため、キーボードが表示されたときにのみ機能します。
つまり、テキストフィールドを選択すると、キーボードが表示され、それに応じてビューが上にスライドしますが、別のテキストフィールドを直接タップすると、キーボードが既に存在するため、ビューが調整されません。
これが私が使用しているコードです。上記のような状況で機能するようにこれを適応させる手助けをいただければ幸いです。
-(void)registerForKeyboardNotifications
{
NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
[center addObserver:self selector:@selector(keyboardDidShow:) name:UIKeyboardDidShowNotification object:nil];
[center addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
// add a tap gesture to drop first responder
UITapGestureRecognizer *tapGR = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapToHideKeyboard:)];
[self.view addGestureRecognizer:tapGR];
}
-(void)keyboardDidShow:(NSNotification *)notification
{
CGRect keyboardFrameW = [[notification.userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
UIWindow *window = [[UIApplication sharedApplication] keyWindow];
CGRect keyboardFrame = [window convertRect:keyboardFrameW toView:self.view];
//Have a minimum space between the keyboard and textfield
CGFloat textFieldBuffer = 40;
CGFloat textFieldKeyboardDifference = 0;
if (activeTextField.frame.origin.y + activeTextField.frame.size.height > keyboardFrame.origin.y) textFieldKeyboardDifference = (activeTextField.frame.origin.y + activeTextField.frame.size.height + textFieldBuffer) - keyboardFrame.origin.y;
else if (activeTextField.frame.origin.y + activeTextField.frame.size.height < keyboardFrame.origin.y) textFieldKeyboardDifference = 0;
[self translateView:self.view toRect:CGRectMake(self.view.frame.origin.x, self.view.frame.origin.y - textFieldKeyboardDifference, self.view.frame.size.width, self.view.frame.size.height) withDuration:0.3];
}
-(void)keyboardWillHide:(NSNotification *)notification
{
//Revert to y origin 0
[self translateView:self.view toRect:CGRectMake(self.view.frame.origin.x, 0, self.view.frame.size.width, self.view.frame.size.height) withDuration:0.3];
}
編集:
が次のように呼び出されたときに、キーボード通知を手動で呼び出してみtextFieldDidBeginEditing
ました。
[self keyboardDidShow:[NSNotification notificationWithName:UIKeyboardDidShowNotification object:nil]];
運がなければ。メソッドが呼び出されますが、うまくいかないため調整は行われません。