我正在创建一个消息传递应用程序时遇到问题,当键盘打开时,我不确定键盘的总大小和框架(字典区域是否打开)。 我想在
中获得总大小和框架textFieldShouldBeginEditing
委托。
答案 0 :(得分:7)
您应该使用UIKeyboardWillChangeFrameNotification。还要确保将CGRect转换为适当的视图,以供横向使用。
在textFieldShouldBeginEditing
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillChange:) name:UIKeyboardWillChangeFrameNotification object:nil];
并编写此方法。
- (void)keyboardWillChange:(NSNotification *)notification {
CGRect keyboardRect = [notification.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
keyboardRect = [self.view convertRect:keyboardRect fromView:nil]; //this is it!
}
在Swift 4中
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillChange(_noti:) ), name: NSNotification.Name.UIKeyboardWillChangeFrame , object: nil)
KeyboardWillChange方法
@objc func keyboardWillChange(_noti:NSNotification)
{
let keyBoard = _noti.userInfo
let keyBoardValue = keyBoard![UIKeyboardFrameEndUserInfoKey]
let fram = keyBoardValue as? CGRect // this is frame
}
答案 1 :(得分:4)
注册UIKeyboardWillShowNotification。
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
并在选择器中获取键盘框架:
- (void)keyboardWillShow:(NSNotification *)iNotification {
NSDictionary *userInfo = [iNotification userInfo];
NSValue *aValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
CGRect keyboardRect = [aValue CGRectValue];
}
答案 2 :(得分:4)
我遇到了这个问题,并通过在键盘上使用通知观察器来解决。
//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;
}