Ajustar interface quando teclado aparece para UITextField ou UITextView

StackOverflow https://stackoverflow.com/questions/402658

  •  03-07-2019
  •  | 
  •  

Pergunta

Eu tenho uma tabela com cada célula que contém um rótulo e um campo de texto. O problema é que quando eu vou editar a última linha, peles de teclado na parte inferior da tabela, e eu não posso ver o que está sendo digitado. Como posso mover minha interface acima do teclado para que eu ver o que está sendo digitado?

Obrigado, Mustafa

Foi útil?

Solução

Você vai querer registrar sua viewController para eventos UIKeyboardDidShowNotification e UIKeyboardWillHideNotification. Quando você começa estes, você deve ajustar os limites da sua mesa; o teclado é de 170 pixels de altura, por isso só diminuir ou aumentar seus limites de mesa de forma adequada, e deve corretamente ajustar para o teclado.

Outras dicas

Este problema é complexo dependendo do cenário UI. Aqui vou discutir um cenário que onde UITextField ou UITextView reside em um UITableViewCell.

  1. Você precisa usar NSNotificationCenter para detectar evento UIKeyboardDidShowNotification. consulte http://iosdevelopertips.com/user-interface/adjust -textfield escondido-a-keyboard.html . Você precisa reduzir o tamanho do quadro UITableView para que ele ocupa apenas a área da tela que não seja coberta pelo teclado.

    1. Se você tocar em um UITableViewCell, o sistema operacional irá posicionar automaticamente o celular dentro da área de visualização de UITableView. Mas isso não acontece quando você toca um UITextView ou UITableViewCell mesmo que ele reside em um UITableViewCell.

Você precisa chamar

[myTableView selectRowAtIndexPath:self.indexPath animated:YES scrollPosition:UITableViewScrollPositionBottom];` 

para programaticamente "tap" da célula.

Se você implementar ambos os pontos, você vai ver o direito posição UITextView / campo acima do teclado. Bare em mente que o UITableViewCell onde reside o UITableView / campo não pode ser mais alto do que a área "não cobertos". Se este não é o caso para você, há uma abordagem diferente para ele, mas eu não vou discutir aqui.

Apenas certifique-se de que tem espaço suficiente rolagem abaixo disso. Porque de acordo com o meu conhecimento do iPhone ajusta e automaticamente mostra a caixa de texto focado no momento suas aparece teclado.

Remoção / comentando as linhas onde a altura rect está sendo modificados parece resolver o problema. Obrigado.

modificou o código:

# define kOFFSET_FOR_KEYBOARD 150.0     // keyboard is 150 pixels height

// Animate the entire view up or down, to prevent the keyboard from covering the author field.
- (void)setViewMovedUp:(BOOL)movedUp
{
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:0.3];

// Make changes to the view's frame inside the animation block. They will be animated instead
// of taking place immediately.
CGRect rect = self.view.frame;
CGRect textViewRect = self.textViewBeingEdited.frame;
CGRect headerViewRect = self.headerView.frame;

if (movedUp) {
    // If moving up, not only decrease the origin but increase the height so the view 
    // covers the entire screen behind the keyboard.
    rect.origin.y -= kOFFSET_FOR_KEYBOARD;
    // rect.size.height += kOFFSET_FOR_KEYBOARD;
} else {
    // If moving down, not only increase the origin but decrease the height.
    rect.origin.y += kOFFSET_FOR_KEYBOARD;
    // rect.size.height -= kOFFSET_FOR_KEYBOARD;
}

self.view.frame = rect;
[UIView commitAnimations];

}

     [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(keyboardWasShown:)
                                                     name:UIKeyboardDidShowNotification
                                                   object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(keyboardWasHidden:)
                                                     name:UIKeyboardDidHideNotification
                                                   object:nil];
        keyboardVisible = NO;

- (void)keyboardWasShown:(NSNotification *)aNotification {
    if ( keyboardVisible )
        return;

    if( activeTextField != MoneyCollected)
    {
        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-300;
        frame.size.height += keyboardSize.height-50;
        [UIView beginAnimations:@"ResizeForKeyboard" context:nil];
        [UIView setAnimationDuration:animationDuration];
        self.view.frame = frame;
        [UIView commitAnimations];

        viewMoved = YES;
    }

    keyboardVisible = YES;
}

- (void)keyboardWasHidden:(NSNotification *)aNotification {
    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-300;
        frame.size.height -= keyboardSize.height-50;
        [UIView beginAnimations:@"ResizeForKeyboard" context:nil];
        [UIView setAnimationDuration:animationDuration];
        self.view.frame = frame;
        [UIView commitAnimations];

        viewMoved = NO;
    }

    keyboardVisible = NO;
}
tabelview.contentInset =  UIEdgeInsetsMake(0, 0, 210, 0);
[tableview scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:your_indexnumber inSection:Your_section]
                 atScrollPosition:UITableViewScrollPositionMiddle animated:NO];

tentar isso a minha codificação isso vai ajudar para u

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top