2008-12-17 6 views
23

coloqué una UITextField en un UIAlertView y se trasladó hacia arriba de modo que el teclado no sería cubrirlo con el siguiente código:UITextField en UIAlertView en iPhone: ¿cómo hacer que responda?

[dialog setDelegate:self]; 
[dialog setTitle:@"Enter Name"]; 
[dialog addButtonWithTitle:@"Cancel"]; 
[dialog addButtonWithTitle:@"OK"]; 
UITextField * nameField = [[UITextField alloc] initWithFrame:CGRectMake(20.0, 45.0, 245.0, 25.0)]; 
[nameField setBackgroundColor:[UIColor whiteColor]]; 
[dialog addSubview:nameField]; 
CGAffineTransform moveUp = CGAffineTransformMakeTranslation(0.0, 100.0); 
[dialog setTransform: moveUp]; 
[dialog show]; 

también tengo el siguiente código para hacer frente a la vista de alertas:

- (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)buttonIndex{  
    NSLog(@"%d", (int) buttonIndex); 
    if (buttonIndex == 1) { // OK pushed 
     NSLog([alert textField].text); // does not log anything 
    } else { 
     // Cancel pushed 
}} 

que también tienen un archivo que contiene UIAlertViewExtended.h:

@class UITextField, UILabel; 

@interface UIAlertView(Extended) 

-(UITextField *)textField; 

@end 

Mi pregunta es ¿cómo puedo obtener el texto introducido el usuario y cómo puedo dismis s el teclado?

Gracias, Ben

+3

iPhone OS 4.0 parece hacer las cosas de transformación automáticamente, probablemente tendremos que introducir una comprobación si su SDK base es 4.0 y el SDK mínimo que admitirá es 3.0, por lo que el código CGAffineTransform se ejecuta solo si el sistema operativo nativo es 3.0 o 3.1, para iPhone OS 4.0 ¡omita esta parte del código! –

Respuesta

31

Para aquellos que pueden cuidar, he aquí una solución de trabajo:

UIAlertView* dialog = [[UIAlertView alloc] init]; 
[dialog setDelegate:self]; 
[dialog setTitle:@"Enter Name"]; 
[dialog setMessage:@" "]; 
[dialog addButtonWithTitle:@"Cancel"]; 
[dialog addButtonWithTitle:@"OK"]; 

nameField = [[UITextField alloc] initWithFrame:CGRectMake(20.0, 45.0, 245.0, 25.0)]; 
[nameField setBackgroundColor:[UIColor whiteColor]]; 
[dialog addSubview:nameField]; 
CGAffineTransform moveUp = CGAffineTransformMakeTranslation(0.0, 100.0); 
[dialog setTransform: moveUp]; 
[dialog show]; 
[dialog release]; 
[nameField release]; 

Asegúrese de que ha creado UITextField * nameField; en su archivo .h, puede obtener el texto que el usuario ingresó haciendo: inputText = [nameField text];

en el - (void) alertView: (UIAlertView *) alert clickedButtonAtIndex: (NSInteger) método buttonIndex.

nota importante: para iOS 4.0+, la CGAffineTransform se realiza automáticamente lo que puede dejar que poco fuera si sólo está dirigido 4.0+. De lo contrario, deberá verificar en qué sistema operativo se encuentra y manejarlo en consecuencia.

+0

Ok, eso funciona bastante bien, pero ¿cómo hago para que los botones se muevan hacia abajo para dejar espacio para el campo de texto? En mi implementación (que comienza como una copia/pega la tuya), tengo 4 botones (Cancelar, foo, bar, baz), y el campo de texto se superpone al botón Cancelar. – Olie

+6

¡Oye! ¿Por qué conservas el 'diálogo' variable? ¿Ya no está asignado por ti? Podría estar equivocado, pero parece que estás filtrando un objeto de esta manera. La regla de oro es que si usted asigna un objeto, debe liberarlo porque ya tiene un conteo de retención de 1. – inkredibl

+1

@inkredibl por el bien de la posteridad, eliminé el retener lo que ocasionó una pérdida de memoria. – Epaga

6

Una forma sencilla de localizar el campo de texto, sin tener una referencia explícita a la misma, es fijar su etiqueta:

nameField.tag = ALERTVIEW_NAMEFIELD; 

Asegúrese de que es diferente de 0 y de otros UIView etiquetas de objeto que pueda tener ¡incluido el cuadro de diálogo principal!

Luego dentro del manejador de alertView:clickedButtonAtIndex:, puede recuperar su campo de texto de esta manera:

UITextField *nameField = (UITextField *)[alertView viewWithTag:ALERTVIEW_NAMEFIELD]; 
+0

Limpio, aprende algo nuevo cada día ... – pix0r

14
+0

El código en la URL es limpio, fácil de usar. – freespace

+2

Gran código. Recomiendo guardar el campo de texto en una variable de instancia. Entonces, no necesita implementar el delegado del campo de texto y puede hacer que renuncie al primer respondedor en 'alertView: willDismissWithButtonIndex:' para deshacerse de los mensajes de la consola "wait_fences: failed to receive reply: 10004003". – gerry3

+0

roto en el simulador 4.3. Bloquea la aplicación. – nemesys

1

Un enfoque bastante agradable es que puede usar los métodos delegados de UITextFieldDelegate para mover el diálogo solo cuando el teclado está activado. Vea abajo.

- (void)textFieldDidBeginEditing:(UITextField *)textField { 
    [UIView beginAnimations:nil context:nil]; 
    [UIView setAnimationDuration:0.5]; 
    [UIView setAnimationDelegate:self]; 

    CGAffineTransform moveUp = CGAffineTransformMakeTranslation(0.0, -20); 
    [dialog setTransform: moveUp]; 

    [UIView commitAnimations]; 
} 

- (BOOL)textFieldShouldReturn:(UITextField *)textField { 
    [UIView beginAnimations:nil context:nil]; 
    [UIView setAnimationDuration:0.5]; 
    [UIView setAnimationDelegate:self]; 

    CGAffineTransform moveDown = CGAffineTransformMakeTranslation(0.0, 0.0); 
    [dialog setTransform: moveDown]; 

    [textField resignFirstResponder]; 

    return YES; 
} 
49

la persona que apoye IOS 5.0 en adelante con ARC, hay esta propiedad alertViewStyle directa se puede establecer:

-(void)showAlertWithTextField{ 
    UIAlertView* dialog = [[UIAlertView alloc] initWithTitle:@"Enter Name" message:@"" delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"Add", nil];  
    [dialog setAlertViewStyle:UIAlertViewStylePlainTextInput]; 

    // Change keyboard type 
    [[dialog textFieldAtIndex:0] setKeyboardType:UIKeyboardTypeNumberPad]; 
    [dialog show]; 
} 

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{ 
    if (buttonIndex == 1) 
     NSLog(@"%@",[[alertView textFieldAtIndex:0]text]); 
} 
+1

sobre el tiempo, obtenemos una forma de hacer esto que no implica hackear el estúpido alertView. +1 – katzenhut

+0

@katzenhut ¡Muy cierto! ¿Hiciste una solicitud de función en [bugreports] (http://bugreport.apple.com)? –

0

Esto es en realidad solamente 1 línea más al código UIAlertView regular. ¡Espero que esto ayude!

UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"test" message:@"This is a alert with a textfield" delegate:self cancelButtonTitle:@"YAY" otherButtonTitles:nil]; 
    alert.alertViewStyle = UIAlertViewStylePlainTextInput; 
    [alert show]; 
    [alert release]; 

sólo se ejecuta en iOS 5 o posterior

1

Esto es para IOS5 y ARC.

-(void)showAlert { 
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"New Album" 
     message:@"Enter a name for the album." 
     delegate:self 
     cancelButtonTitle:@"Cancel" 
     otherButtonTitles:@"Save", nil]; 
    alertView.alertViewStyle = UIAlertViewStylePlainTextInput; 

    UITextField* textfield = [alertView textFieldAtIndex:0]; 
    textfield.placeholder = @"Title"; 

    [alertView show]; 
} 

-(void)alertView:(UIAlertView *)alertView 
    didDismissWithButtonIndex:(NSInteger)buttonIndex 
{ 
    if (buttonIndex != 1) { 
     NSLog(@"Cancel"); 
     return; 
    } 
    UITextField* textfield = [alertView textFieldAtIndex:0]; 
    NSLog(@"Save. text: %@", textfield.text); 
} 
0

gustaría añadir un pequeño ajuste a la respuesta de iWasRobbed:

GenericAlertDialogs.m:

+ (void)displayInputDialog:(NSString*)title delegate:(id<UIAlertViewDelegate>)delegate textFiled:(UITextField*)txtField 
{ 
    UIAlertView* dialog = [[UIAlertView alloc] init]; 
    [dialog setDelegate:delegate]; 
    [dialog setTitle:title]; 
    [dialog setMessage:@" "]; 
    [dialog addButtonWithTitle:@"Cancel"]; 
    [dialog addButtonWithTitle:@"OK"]; 

    if(UIInterfaceOrientationIsPortrait([[UIApplication sharedApplication] statusBarOrientation])) 
    { 
     txtField.frame = CGRectMake(20.0, 45.0, 245.0, 25.0); 
    } 
    else 
    { 
     txtField.frame = CGRectMake(20.0, 30.0, 245.0, 25.0); 
    } 

    [txtField becomeFirstResponder]; 
    [txtField setBackgroundColor:[UIColor whiteColor]]; 
    [dialog addSubview:txtField]; 
    [dialog show]; 
} 

algún otro archivo .m (implementa UIAlertViewDelegate)

self->txtChangeName = [[UITextField alloc] init]; 
[GenericAlertDialogs displayInputDialog:@"Some title...:" 
           delegate:self 
           textFiled:txtChangeName]; 

El UIAlertViewDelegate manejo protocolo:

- (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)buttonIndex 
{ 
    if(buttonIndex == 1) 
    { 
     if([txtChangeName.text length] > 0) 
     { 
      self->userInput = [txtChangeName text]; 
     } 
    } 
    self->txtChangeName = nil; 
} 

iOS 4+ compatible.

Cuestiones relacionadas