2010-02-21 25 views
21

Estoy utilizando UITextField para recibir entradas de usuario. Sin embargo, dado que mis campos de texto están hacia la mitad/parte inferior de la punta, se oculta cuando aparece el teclado. ¿Hay alguna forma de deslizarlo junto con el teclado para que esté en la parte superior del teclado durante la selección? Además, dado que también estoy usando el teclado numérico, ¿hay alguna manera fácil de incluir un botón hecho en alguna parte?iPhone - El teclado oculta TextField

Gracias por la ayuda.

+0

Esto es, posiblemente, una víctima de: http://stackoverflow.com/questions/1775860/uitextfield-move-view-when -keyboard-aparece, sin embargo, no soy un desarrollador de iPhone, por lo que me inclinaré ante la comunidad para decidir. – Kev

+0

Esto puede ser una solución para usted: - http://stackoverflow.com/a/17707278/1582217 –

Respuesta

16

Para desplazarse cuando aparece el teclado, me gusta this tutorial de Cocoa With Love.

Para cerrar el teclado numérico, puede put a custom "Done" button on the keypad o hacer un botón invisible sobre el resto de la pantalla. He hecho esto último con código, pero this tutorial usa Interface Builder.

+1

el tercer enlace está roto :( – osdamv

+0

Basado en el primer enlace tutorial en esta respuesta se me ocurrió esta idea: https: //gist.github.com/siannopollo/7892526 Lleva a cabo un desplazamiento menos consistente. – siannopollo

1

Esta situación es una mierda en el iPhone. Lo que se supone que debes hacer es diseñar tu interfaz de tal manera que los campos estén visibles cuando aparezca el teclado, o cambiar el campo cuando aparezca el teclado. (Y vuelve a bajar cuando hayas terminado)

Te sugiero que veas algunas aplicaciones de Apple, como Contactos o Configuraciones, para ver cómo están lidiando con esto.

Además, estoy seguro de que el iPhone HIG tiene algo que decir al respecto.

26

He hecho una aplicación simple para este problema. Verifica automáticamente la posición del campo de texto y si el teclado lo oculta, se moverá automáticamente según las necesidades.

 

- (void)textFieldDidBeginEditing:(UITextField *)textField 
{ 
    [self animateTextField:textField up:YES]; 
} 


- (void)textFieldDidEndEditing:(UITextField *)textField 
{ 
    [self animateTextField:textField up:NO]; 
} 


- (void) animateTextField: (UITextField*) textField up: (BOOL) up 
{ 
    int animatedDistance; 
    int moveUpValue = textField.frame.origin.y+ textField.frame.size.height; 
    UIInterfaceOrientation orientation = 
    [[UIApplication sharedApplication] statusBarOrientation]; 
    if (orientation == UIInterfaceOrientationPortrait || 
     orientation == UIInterfaceOrientationPortraitUpsideDown) 
    { 

     animatedDistance = 216-(460-moveUpValue-5); 
    } 
    else 
    { 
     animatedDistance = 162-(320-moveUpValue-5); 
    } 

    if(animatedDistance>0) 
    { 
     const int movementDistance = animatedDistance; 
     const float movementDuration = 0.3f; 
     int movement = (up ? -movementDistance : movementDistance); 
     [UIView beginAnimations: nil context: nil]; 
     [UIView setAnimationBeginsFromCurrentState: YES]; 
     [UIView setAnimationDuration: movementDuration]; 
     self.view.frame = CGRectOffset(self.view.frame, 0, movement);  
     [UIView commitAnimations]; 
    } 
} 

-(BOOL)textFieldShouldReturn:(UITextField *)textField { 

    [textField resignFirstResponder]; 
    return YES; 
} 
 
+0

Estoy en mi octavo campo de texto y he hecho clic en tabbar, como si hubiera desaparecido toda una vista mágica. ¿Por qué? – Dee

+0

@Dee Por favor, dame el código. . Puedo revisar y me pondré en contacto con usted. – ValayPatel

+0

Si está usando este código, use '[UIView transitionWithView ...]' en lugar de '[UIView beginAnimations ...], [UIView setAnimationBegins ...], [UIView setAnimationDuration ...], [UIView commitAnimations] .' – DevC

3

Usar este código:

- (void)viewDidAppear:(BOOL)animated 
{ 
[super viewDidAppear:animated]; 
// register for keyboard notifications 
[[NSNotificationCenter defaultCenter] addObserver:self 
             selector:@selector(keyboardDidShow:) 
              name:UIKeyboardDidShowNotification 
              object:self.view.window]; 
[[NSNotificationCenter defaultCenter] addObserver:self 
             selector:@selector(keyboardDidHide:) 
              name:UIKeyboardDidHideNotification 
              object:self.view.window]; 
} 


- (void)viewDidDisappear:(BOOL)animated { 
// unregister for keyboard notifications while not visible. 
[[NSNotificationCenter defaultCenter] removeObserver:self 
               name:UIKeyboardDidShowNotification 
               object:nil]; 
[[NSNotificationCenter defaultCenter] removeObserver:self 
               name:UIKeyboardDidHideNotification 
               object:nil]; 
} 

- (void)keyboardDidHide:(NSNotification *)n 
{ 
CGRect viewFrame = scrollView.frame; 
UIDeviceOrientation orientSide = [[UIDevice currentDevice] orientation]; 
if ((orientSide == UIDeviceOrientationLandscapeRight) || (orientSide == UIDeviceOrientationLandscapeLeft)) 
    viewFrame.size.height += 140; 
else viewFrame.size.height += 216; //portrait mode 
scrollView.frame = viewFrame; 
keyboardVisible = NO; 
} 

- (void)keyboardDidShow:(NSNotification *)n 
{ 
CGRect viewFrame = scrollView.frame; 
UIDeviceOrientation orientSide = [[UIDevice currentDevice] orientation]; 
if ((orientSide == UIDeviceOrientationLandscapeRight) || (orientSide == UIDeviceOrientationLandscapeLeft)) 
    viewFrame.size.height -= 140; 
else viewFrame.size.height -= 216; //portrait mode 
scrollView.frame = viewFrame; 
keyboardVisible = YES; } 

- (BOOL)textFieldShouldReturn:(UITextField *)textField 
{ 
[textField resignFirstResponder]; 
return YES; 
} 

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation 
{ 
CGRect viewFrame = scrollView.frame; 
if ((interfaceOrientation == UIDeviceOrientationLandscapeRight) || (interfaceOrientation == UIDeviceOrientationLandscapeLeft)) //wants to change to landscape mode 
    if (keyboardVisible == NO)//currently in portrait,check if keyboard was present 
      viewFrame.size = CGSizeMake(480,250); 
    else viewFrame.size = CGSizeMake(480,170); 
else {//wants to change to portrait mode 
    if (keyboardVisible == NO)//currently in landscape,check if keyboard was present 
     viewFrame.size = CGSizeMake(320,416); 
    else viewFrame.size = CGSizeMake(320,200); 
} 
scrollView.frame = viewFrame; 

return YES; 
} 

Obras para el modo de paisaje también, pero sólo para iPhone. Para iPad, cambie la configuración de cuadro en consecuencia. El método textFieldShouldReturn: hará que el teclado se oculte cuando se presiona return. Espero que esto ayude ...

+0

¿Qué es el parámetro scrollView? – Dejell

+0

Es el nombre de su scrollView que contiene los campos de texto. – tipycalFlow

+0

Esto puede causar problemas, porque viewDidUnload nunca se llamará en iOS 6 y posteriores, por lo que realmente no anula el registro de los oyentes. – ljboy

3

El siguiente código funciona perfecto para mí.

[textFieldFocused becomeFirstResponder]; 
[self.view addSubview:startView]; 
[textFieldFocused resignFirstResponder]; 
+0

¿puedes describir qué es ** startView ** aquí? – swiftBoy

+0

startView es solo otra vista, puede ser cualquier vista. la clave es becomeFirstResponder y luego renunciar a ella. – idea2real

0

Sé que llegué un poco tarde respondiendo esto, pero encontré una solución muy simple. Si usa un controlador UITableView en lugar de un UIViewController que tiene un tableView como objeto, este problema no aparece.

Al hacer clic en el campo de texto que está en la parte inferior de la tabla, el teclado emerge y la vista de tabla se desplaza automáticamente hasta que el campo de texto que se está editando sea visible.

Sin embargo, el desplazamiento automático no funciona cuando utilizamos el botón de retorno en el teclado. En este escenario, hemos desplazado manualmente la tabla hacia arriba para ver el campo de texto.

espero que esto ayude a

0

He estado buscando a través de innumerables respuestas a preguntas similares. Para aplicaciones básicas de pantalla única, esta solución funciona como un encanto y es increíblemente fácil de implementar: https://github.com/michaeltyson/TPKeyboardAvoiding

Sin duda, hay soluciones más elegantes, pero esto hará el trabajo de manera rápida.

0

¡Es tan simple como configurar el modo UITableView en edición!

- (void)viewDidLoad { 

    [super viewDidLoad]; 

    [self.tableView setEditing:YES]; 
} 

Si desea ocultar un bubbels eliminar, a la izquierda de una celda a continuación, poner en práctica un método UITableViewDelegate:

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath { 

    return NO; 
} 
0
- (void)textFieldDidBeginEditing:(UITextField *)textField 
{ 
    NSLog(@"%f",textField.frame.origin.y); 

    CGPoint scrollPoint = CGPointMake(0, textField.frame.origin); 
    [scrollView setContentOffset:scrollPoint animated:YES]; 
} 

- (void)textFieldDidEndEditing:(UITextField *)textField 
{ 
    [scrollView setContentOffset:CGPointZero animated:YES]; 
} 
0
- (void)textFieldDidBeginEditing:(UITextField *)textField 
{ 
    [self animateTextField:textField up:YES]; 
} 

Utilice este código en tu controlador de vista .m archivo ... Al usar este código al hacer clic en el campo de texto, aparecerá el teclado. Una vez que haga clic en su vista, el teclado se ocultará. Espero que esto sea útil ...

3

si alguien lo necesita, `ve traducido la solución de ValayPatel al veloz

func animatedTextField(textField: UITextField, up: Bool){ 
    var animatedDistance : Int = 0 
    let moveUpValue : Int = Int(textField.frame.origin.y) + Int(textField.frame.size.height) 

    switch UIDevice.currentDevice().orientation { 
    case .Portrait , .PortraitUpsideDown: 
     animatedDistance = 216 - (460 - moveUpValue - 5) 
    default: 
     animatedDistance = 162 - (320 - moveUpValue - 5) 
    } 

    if (animatedDistance > 0){ 

     let movementDistance : Int = animatedDistance 
     let movementDuration : Float = 0.3 
     let movement = up ? -movementDistance : movementDistance 
     UIView.beginAnimations(nil, context: nil) 
     UIView.setAnimationBeginsFromCurrentState(true) 
     UIView.setAnimationDuration(NSTimeInterval(movementDuration)) 
     self.view.frame = CGRectOffset(self.view.frame, 0, CGFloat(movement)) 
     UIView.commitAnimations() 

    } 

} 
+0

Cambie la línea anterior a 'self.view.frame = self.view.frame.offsetBy (dx: 0, dy: CGFloat (movimiento))' –

Cuestiones relacionadas