I have subclass of UITextField
. I want to know when keyboard is visible. This will help me to move all view up if the keyboard is hiding my text field.
In my subclass I add observer as follows:
- (id)initWithCoder:(NSCoder *)aDecoder{
if (self = [super initWithCoder:aDecoder]) {
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardIsVisible:) name:UIKeyboardDidShowNotification object:nil];
}
return self;
}
I expect to catch the size of the keyboard:
/* Get height when keyboard is visible */
- (void)keyboardIsVisible:(NSNotification*)notification
{
NSDictionary* keyboardInfo = [notification userInfo];
NSValue* keyboardFrameBegin = [keyboardInfo valueForKey:UIKeyboardFrameBeginUserInfoKey];
CGRect keyboardFrameBeginRect = [keyboardFrameBegin CGRectValue];
_keyboardHeight =keyboardFrameBeginRect.size.height;
}
I will use ivar _keyboardHeight
to decide if I have to move keyboard:
/* Move keyboard */
-(void)showKeyboardWithMove {
CGRect screenRect = [[UIScreen mainScreen] bounds];
////CGFloat screenWidth = screenRect.size.width;
CGFloat screenHeight = screenRect.size.height;
if (self.frame.origin.y + self.frame.size.height > screenHeight - _keyboardHeight) {
double offset = screenHeight - _keyboardHeight - self.frame.origin.y - self.frame.size.height;
CGRect rect = CGRectMake(0, offset, self.superview.frame.size.width, self.superview.frame.size.height);
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:0.3];
self.superview.frame = rect;
[UIView commitAnimations];
}
}
From my view controller class I call showKeyboardWithMove
:
- (void)textFieldDidBeginEditing:(MyCustomTextField *)textField
{
// Call method for moving control when Keyboard is shown and hides it
[textField showKeyboardWithMove];
}
- (void)textFieldDidEndEditing:(MyCustomTextField *)textField
{
// Call method for returning control when Keyboard is hidden
[textField hideKeyboardWithMove];
}
The problem is that keyboardIsVisible
is not fire when I first show keyboard. So I think that my observer is not properly coded. Any ideas?