如何使用 iOS 获取 UIKeyboard 大小

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3546571/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 17:36:01  来源:igfitidea点击:

How to get UIKeyboard size with iOS

iosobjective-ciphonesoft-keyboard

提问by Tharindu Madushanka

Is there some way to get UIKeyboard size programmatically. 216.0f height and 162.0f height in landscape.

有没有办法以编程方式获取 UIKeyboard 大小。横向 216.0f 高度和 162.0f 高度。

Following seem to be deprecated. Is there some way that works without any warning in both 3.0 iPhone OS SDK and 4.0 iPhone OS SDK to do this..

以下似乎已被弃用。有没有什么方法可以在 3.0 iPhone OS SDK 和 4.0 iPhone OS SDK 中没有任何警告地工作来做到这一点..

CGSize keyBoardSize = [[[note userInfo]
                        objectForKey:UIKeyboardBoundsUserInfoKey] CGRectValue].size;

回答by James Bedford

You can get the keyboard size from the userInfodictionary using the UIKeyboardFrameBeginUserInfoKeyand the UIKeyboardFrameEndUserInfoKeyinstead.

您可以userInfo使用UIKeyboardFrameBeginUserInfoKeyUIKeyboardFrameEndUserInfoKey从字典中获取键盘大小。

These two keys return a NSValueinstance containing a CGRectthat holds the position and size of the keyboard at both the start and end points of the keyboard's show/hide animation.

这两个键返回一个NSValue实例,其中包含CGRect在键盘显示/隐藏动画的开始点和结束点处保存键盘位置和大小的 。

Edit:

编辑:

To clarify, the userInfodictionary comes from an NSNotificationinstance. It's passed to your method that you register with an observer. For example,

澄清一下,userInfo字典来自NSNotification实例。它传递给您向观察者注册的方法。例如,

- (void)someMethodWhereYouSetUpYourObserver
{
    // This could be in an init method.
    [[NSNotificationCenter defaultCenter] addObserver:self 
                    selector:@selector(myNotificationMethod:) 
                    name:UIKeyboardDidShowNotification 
                    object:nil];
}

- (void)myNotificationMethod:(NSNotification*)notification
{
    NSDictionary* keyboardInfo = [notification userInfo];
    NSValue* keyboardFrameBegin = [keyboardInfo valueForKey:UIKeyboardFrameBeginUserInfoKey];
    CGRect keyboardFrameBeginRect = [keyboardFrameBegin CGRectValue];
}

Edit 2:

编辑2:

Also, please don't forget to remove yourself as an observer in your deallocmethod! This is to avoid a crash that would occur when the notification center tries to notify your object after its been freed.

另外,请不要忘记在您的dealloc方法中删除自己作为观察者!这是为了避免在释放对象后通知中心尝试通知您的对象时发生的崩溃。

回答by Jeffrey Sun

You should use the UIKeyboardWillChangeFrameNotificationinstead, because some international keyboards, like the Chinese keyboard, will change frames during use. Also make sure to convert the CGRectinto the proper view, for landscape use.

你应该UIKeyboardWillChangeFrameNotification改用 ,因为一些国际键盘,比如中文键盘,在使用过程中会改变框架。还要确保将其CGRect转换为正确的视图,以供景观使用。

//some method like viewDidLoad, where you set up your observer.
[[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!
}

回答by Kamel

Here's how I finally made works. I combined suggestions and codes from different answers. Features: dismissing keyboard, moving text fields above keyboard while editing and setting "Next" and "Done" keyboard return type.REPLACE "..." with more fields

这是我最终制作作品的方式。我结合了来自不同答案的建议和代码。功能:关闭键盘,在编辑和设置“下一步”和“完成”键盘返回类型时移动键盘上方的文本字段。用更多字段替换“...”

static const CGFloat ANIMATION_DURATION = 0.4;
static const CGFloat LITTLE_SPACE = 5;
CGFloat animatedDistance;
CGSize keyboardSize;

@interface ViewController () <UITextFieldDelegate>
 @property (weak, nonatomic) IBOutlet UITextField *firstNameTXT;
  .....// some other text fields
 @property (weak, nonatomic) IBOutlet UITextField *emailTXT;
@end

@implementation ViewController
- (void)viewDidLoad{
.....
// add tap gesture to help in dismissing keyboard
UITapGestureRecognizer * tapGesture = [[UITapGestureRecognizer alloc]
                                       initWithTarget:self
                                       action:@selector(tapScreen:)];// outside textfields

[self.view addGestureRecognizer:tapGesture];

// set text fields return key type to Next, last text field to Done
[self.firstNameTXT setReturnKeyType:UIReturnKeyNext];
.....
[self.emailTXT setReturnKeyType:UIReturnKeyDone];

// set text fields tags
[self.firstNameTXT setTag:0];
....// more text fields
[self.emailTXT setTag:5];

// add keyboard notification
[[NSNotificationCenter defaultCenter] addObserver:self     selector:@selector(keyboardDidShow:) name:UIKeyboardDidShowNotification object:nil];
}
[[NSNotificationCenter defaultCenter] addObserver:self      selector:@selector(keyboardDidHide:) name:UIKeyboardDidHideNotification object:nil];
}

// dismiss keyboard when tap outside text fields
- (IBAction)tapScreen:(UITapGestureRecognizer *)sender {
  if([self.firstNameTXT isFirstResponder])[self.firstNameTXT resignFirstResponder];
  ...
  if([self.emailTXT isFirstResponder])[self.emailTXT  resignFirstResponder];

  }
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
   if(textField.returnKeyType==UIReturnKeyNext) {
     // find the text field with next tag
     UIView *next = [[textField superview] viewWithTag:textField.tag+1];
     [next becomeFirstResponder];
   } else if (textField.returnKeyType==UIReturnKeyDone || textField.returnKeyType==UIReturnKeyDefault) {
    [textField resignFirstResponder];
 }
return YES;
}

// Moving current text field above keyboard
-(BOOL) textFieldShouldBeginEditing:(UITextField*)textField{
   CGRect viewFrame = self.view.frame;
   CGRect textFieldRect = [self.view.window convertRect:textField.bounds fromView:textField];
   CGRect viewRect = [self.view.window convertRect:self.view.bounds fromView:self.view];
   CGFloat textFieldBottomLine = textFieldRect.origin.y + textFieldRect.size.height + LITTLE_SPACE;//

   CGFloat keyboardHeight = keyboardSize.height;

   BOOL isTextFieldHidden = textFieldBottomLine > (viewRect.size.height - keyboardHeight)? TRUE :FALSE;
  if (isTextFieldHidden) {
    animatedDistance = textFieldBottomLine - (viewRect.size.height - keyboardHeight) ;
    viewFrame.origin.y -= animatedDistance;
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationBeginsFromCurrentState:YES];
    [UIView setAnimationDuration:ANIMATION_DURATION];
    [self.view setFrame:viewFrame];
    [UIView commitAnimations];
  }
  return YES;
}

-(void) restoreViewFrameOrigionYToZero{
  CGRect viewFrame = self.view.frame;
  if (viewFrame.origin.y != 0) {
    viewFrame.origin.y = 0;
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationBeginsFromCurrentState:YES];
    [UIView setAnimationDuration:ANIMATION_DURATION];
    [self.view setFrame:viewFrame];
    [UIView commitAnimations];
  }
}

-(void)keyboardDidShow:(NSNotification*)aNotification{
   NSDictionary* info = [aNotification userInfo];
   keyboardSize = [[info objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;
 }

-(void)keyboardDidHide:(NSNotification*)aNotification{
   [self restoreViewFrameOrigionYToZero];// keyboard is dismissed, restore frame view to its  zero origin
}
@end

回答by omi5489

On swift 4

快速 4

override func viewDidLoad() {
    super.viewDidLoad()
    NotificationCenter.default.addObserver(self, selector: #selector(getInfo(notif:)), name: .UIKeyboardDidShow , object: nil)
}

and then:

进而:

@objc func getInfo(notif: NSNotification) -> Void {  
    guard let userInfo = notif.userInfo else {return}

    if let myData = userInfo["UIKeyboardFrameBeginUserInfoKey"] as? CGRect {
        print(myData.width)
        print(myData.height)
    }
}