【发布时间】:2015-09-22 05:30:01
【问题描述】:
我在创建消息传递应用程序时遇到问题,当键盘打开时,我不确定键盘的总大小和框架(字典区域是否打开)。 我想在
中获得总尺寸和框架textFieldShouldBeginEditing
委托。
【问题讨论】:
标签: ios iphone uikeyboard
我在创建消息传递应用程序时遇到问题,当键盘打开时,我不确定键盘的总大小和框架(字典区域是否打开)。 我想在
中获得总尺寸和框架textFieldShouldBeginEditing
委托。
【问题讨论】:
标签: ios iphone uikeyboard
您应该使用 UIKeyboardWillChangeFrameNotification 。还要确保将 CGRect 转换为正确的视图,以供横向使用。
在你的textFieldShouldBeginEditing中设置NSNotificationCenter
[[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
}
【讨论】:
注册 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];
}
【讨论】:
我遇到了这个问题并通过在键盘上使用通知观察器解决了。
//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;
}
【讨论】: