Как получить размер UIKeyboard с iOS - PullRequest
66 голосов
/ 23 августа 2010

Есть ли какой-нибудь способ получить размер UIKeyboard программно.216.0f высоты и 162.0f высоты в альбомной ориентации.

Следующее представляется устаревшим.Есть ли способ, который работает без какого-либо предупреждения в 3.0 iPhone OS SDK и 4.0 iPhone OS SDK, чтобы сделать это ..

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

Ответы [ 4 ]

140 голосов
/ 16 марта 2011

Размер клавиатуры можно получить из словаря userInfo, используя UIKeyboardFrameBeginUserInfoKey и UIKeyboardFrameEndUserInfoKey вместо.

Эти две клавиши возвращают экземпляр NSValue, содержащий CGRect, который содержит положение и размер клавиатуры как в начальной, так и в конечной точках анимации отображения / скрытия клавиатуры.

Изменить:

Для пояснения, словарь 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];
}

Редактировать 2:

Также, пожалуйста, не забудьте удалить себя в качестве наблюдателя в вашем dealloc методе! Это сделано для того, чтобы избежать сбоя, который может возникнуть, когда центр уведомлений пытается уведомить ваш объект после его освобождения.

47 голосов
/ 04 августа 2014

Вместо этого следует использовать 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!
}
3 голосов
/ 06 августа 2014

Вот как я наконец заработал.Я объединил предложения и коды из разных ответов.Особенности: отмена клавиатуры, перемещение текстовых полей над клавиатурой при редактировании и настройка «Далее» и «Готово». Тип возврата клавиатуры. ОБРАТИТЬ «...» с дополнительными полями

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
0 голосов
/ 03 августа 2017

На Свифт 4

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

и затем:

@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)
    }
}
...