Reputation: 191
I am having trouble while i am creating a messaging app, When keyboard is opened i am not sure about total size and frame for Keyboard (dictionary area is opened or not). I want to get total size and frame in
textFieldShouldBeginEditing
delegate.
Upvotes: 1
Views: 650
Reputation:
You should use the UIKeyboardWillChangeFrameNotification . Also make sure to convert the CGRect into the proper view, for landscape use.
Set NSNotificationCenter in your textFieldShouldBeginEditing
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillChange:) name:UIKeyboardWillChangeFrameNotification object:nil];
and write this method.
- (void)keyboardWillChange:(NSNotification *)notification {
CGRect keyboardRect = [notification.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
keyboardRect = [self.view convertRect:keyboardRect fromView:nil]; //this is it!
}
In Swift 4
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillChange(_noti:) ), name: NSNotification.Name.UIKeyboardWillChangeFrame , object: nil)
KeyboardWillChange Method
@objc func keyboardWillChange(_noti:NSNotification)
{
let keyBoard = _noti.userInfo
let keyBoardValue = keyBoard![UIKeyboardFrameEndUserInfoKey]
let fram = keyBoardValue as? CGRect // this is frame
}
Upvotes: 7
Reputation:
I have faced this problem and solved by using notification observer on keyboard.
//set observer in textFieldShouldBeginEditing like
-(BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(myNotificationMethod:) name:UIKeyboardWillChangeFrameNotification object:nil];
return YES;
}
// method implementation
- (void)myNotificationMethod:(NSNotification*)notification
{
NSDictionary* keyboardInfo = [notification userInfo];
NSValue* keyboardFrameBegin = [keyboardInfo valueForKey:UIKeyboardFrameEndUserInfoKey];
CGRect keyboardFrameBeginRect = [keyboardFrameBegin CGRectValue];
NSLog(@"%@",keyboardFrameBegin);
NSLog(@"%f",keyboardFrameBeginRect.size.height);
}
//remove observer
- (BOOL)textFieldShouldEndEditing:(UITextField *)textField{
[[NSNotificationCenter defaultCenter ]removeObserver:self];
return YES;
}
Upvotes: 4
Reputation: 2281
Register for UIKeyboardWillShowNotification.
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
and in the selector get the keyboard frame:
- (void)keyboardWillShow:(NSNotification *)iNotification {
NSDictionary *userInfo = [iNotification userInfo];
NSValue *aValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
CGRect keyboardRect = [aValue CGRectValue];
}
Upvotes: 4