iPhone SDK: TextView, клавиатура в ландшафтном режиме

Как мне убедиться, что текстовое представление отображается, а клавиатура не закрывает текстовое представление в альбомной ориентации.

Используя UICatalog, я создал TextViewController, который работает. В нем есть два метода вызова клавиатуры и проверки того, что textView расположен над клавиатурой. он просто отлично работает в портретном режиме.

У меня работает альбомный режим, но textView все еще помещается в верхнюю часть iPhone, чтобы компенсировать клавиатуру в портретном режиме.

Я изменил способы отображения клавиатур.

Ниже приведен код для этих методов: (Я просто покажу код для показа, так как код скрытия будет обратным ..

- (void)keyboardWillShow:(NSNotification *)aNotification 
{
 UIInterfaceOrientation orientation = [[UIApplication sharedApplication] statusBarOrientation];
 if (orientation == UIInterfaceOrientationPortrait) {
   // the keyboard is showing so resize the table's height
  CGRect keyboardRect = [[[aNotification userInfo] objectForKey:UIKeyboardBoundsUserInfoKey] CGRectValue];
  NSTimeInterval animationDuration = [[[aNotification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
  CGRect frame = self.view.frame;
  frame.size.height -= keyboardRect.size.height;
  [UIView beginAnimations:@"ResizeForKeyboard" context:nil];
  [UIView setAnimationDuration:animationDuration];
  self.view.frame = frame;
  [UIView commitAnimations];
 } else if (orientation == UIInterfaceOrientationLandscapeLeft) {
  NSLog(@"Left"); // Verijderen later
  CGRect keyboardRect = [[[aNotification userInfo] objectForKey:UIKeyboardBoundsUserInfoKey] CGRectValue];
  NSTimeInterval animationDuration = [[[aNotification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
  CGRect frame = self.view.frame;
  frame.size.width -= keyboardRect.size.height;
  [UIView beginAnimations:@"ResizeForKeyboard" context:nil];
  [UIView setAnimationDuration:animationDuration];
  self.view.frame = frame;
  [UIView commitAnimations];
 } else if (orientation == UIInterfaceOrientationLandscapeRight){
  NSLog(@"Right"); // verwijderen later.
  CGRect keyboardRect = [[[aNotification userInfo] objectForKey:UIKeyboardBoundsUserInfoKey] CGRectValue];
  NSTimeInterval animationDuration = [[[aNotification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
  CGRect frame = self.view.frame;
  frame.size.width -= keyboardRect.size.width;
  [UIView beginAnimations:@"ResizeForKeyboard" context:nil];
  [UIView setAnimationDuration:animationDuration];
  self.view.frame = frame;
  [UIView commitAnimations];
 }

}

Я знаю, что мне нужно изменить строку frame.size.height -= keyboardRect.size.height, но, похоже, она не работает.

Я пробовал frame.size.width -= keyboardRect.size.height, но ничего не вышло. Потеря keyboardRect и frame все вместе работают, однако, конечно, клавиатура закрывает текстовое представление ........


person Arnold    schedule 14.05.2010    source источник


Ответы (3)


Я обнаружил, что приведенный выше код не будет работать в ландшафтном режиме на iPad.

Примечание: я перемещаю все поля, так как в моем случае это то, что мне нужно :-)

- (void)keyboardWillShow:(NSNotification*)aNotification {
// Only do for Landscape Mode

    if (UIInterfaceOrientationIsLandscape([self interfaceOrientation])){
        NSDictionary *info = [aNotification userInfo];
        NSValue *aValue = [info objectForKey:UIKeyboardBoundsUserInfoKey];
        CGSize keyboardSize = [aValue CGRectValue].size;

        NSTimeInterval animationDuration = 0.300000011920929;
        CGRect frame = self.view.frame;
        frame.origin.x -= keyboardSize.height-44;
        frame.origin.y -= keyboardSize.height-44;
        frame.size.height += keyboardSize.height-44;
        [UIView beginAnimations:@"ResizeForKeyboard" context:nil];
        [UIView setAnimationDuration:animationDuration];
        self.view.frame = frame;
        [UIView commitAnimations];

        viewMoved = YES;
    }
    keyboardInUse = YES;
}

- (void)keyboardWillHide:(NSNotification*)aNotification {
    if (UIInterfaceOrientationIsLandscape([self interfaceOrientation])){
        if (viewMoved) {

            NSDictionary *info = [aNotification userInfo];
            NSValue *aValue = [info objectForKey:UIKeyboardBoundsUserInfoKey];
            CGSize keyboardSize = [aValue CGRectValue].size;

            NSTimeInterval animationDuration = 0.300000011920929;
            CGRect frame = self.view.frame;
            frame.origin.y += keyboardSize.height-44;
            frame.origin.x += keyboardSize.height-44;
            frame.size.height -= keyboardSize.height-44;
            [UIView beginAnimations:@"ResizeForKeyboard" context:nil];
            [UIView setAnimationDuration:animationDuration];
            self.view.frame = frame;
            [UIView commitAnimations];

            viewMoved = NO;
        }
    }
    keyboardInUse = NO;
}
person Don    schedule 25.05.2011

Если вы думаете, что вам нужен другой код для разных ориентаций, вы делаете что-то еще не так. После изменения ориентации и ответа вашего супервизора значение, которое необходимо изменить, должно всегда быть высотой фрейма.

person matt    schedule 13.06.2010
comment
Если это так, то почему этот код: CGRect keyboardRect = [[[aNotification userInfo] objectForKey: UIKeyboardBoundsUserInfoKey] CGRectValue]; NSTimeInterval animationDuration = [[[aNotification userInfo] objectForKey: UIKeyboardAnimationDurationUserInfoKey] doubleValue]; CGRect frame = self.view.frame; frame.size.height - = keyboardRect.size.height; [UIView beginAnimations: @ResizeForKeyboard context: nil]; [UIView setAnimationDuration: animationDuration]; self.view.frame = кадр; [UIView commitAnimations]; в результате в ландшафтном режиме изображение перемещается вправо? - person Arnold; 14.06.2010

Вот код, который я использую для этой цели. Он работает как на iPad, так и на iPhone в ландшафтном и портретном режимах (на основе кода из документации Apple):

// Call this method somewhere in your view controller setup code.
- (void)registerForKeyboardNotifications
{
[[NSNotificationCenter defaultCenter] addObserver:self
                                         selector:@selector(keyboardWasShown:)
                                             name:UIKeyboardDidShowNotification object:nil];

[[NSNotificationCenter defaultCenter] addObserver:self
                                         selector:@selector(keyboardWillBeHidden:)
                                             name:UIKeyboardWillHideNotification object:nil];

}

// Called when the UIKeyboardDidShowNotification is sent.
- (void)keyboardWasShown:(NSNotification*)aNotification
{
NSDictionary* info = [aNotification userInfo];
CGSize kbSize = [[info objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;

float offset;
if UIInterfaceOrientationIsPortrait(self.interfaceOrientation)
    offset = kbSize.height;
else
    offset = kbSize.width;

[UIView animateWithDuration:0.5
                 animations:^{
                     CGRect frameTxtField = myTextField.frame;
                     frameTxtField.origin.y -= offset;
                     myTextField.frame = frameTxtField;
                 }
 ];  

}

// Called when the UIKeyboardWillHideNotification is sent
- (void)keyboardWillBeHidden:(NSNotification*)aNotification
{
NSDictionary* info = [aNotification userInfo];
CGSize kbSize = [[info objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;

float offset;
if UIInterfaceOrientationIsPortrait(self.interfaceOrientation)
    offset = kbSize.height;
else
    offset = kbSize.width;

[UIView animateWithDuration:0.5
                 animations:^{
                     CGRect frameTxtField = myTextField.frame;
                     frameTxtField.origin.y += offset;
                     myTextField.frame = frameTxtField;
                 }
 ];  
}

Не забудьте вызвать метод registerForKeyboardNotifications (например, в viewDidLoad).

person RawMean    schedule 15.12.2011