2010-06-10 31 views
6

Estoy harto de escritura básica UIAlertView de, es decir:¿Escribir una función para UIAlertView?

UIAlertView *alert = [[UIAlertView alloc] initWith...]] //etc 

lugar de hacer esto, es posible poner todo esto en una función de "ayudante", donde puedo devolver el buttonIndex, o lo que sea una alerta por lo general, vuelve?

Para una función de ayuda simple, supongo que podría alimentar parámetros para el título, mensaje, no estoy seguro de si puede pasar delegados en un parámetro, o información del paquete.

En pseudo-código, podría ser así:

someValueOrObject = Print_Alert(Title="", Message="", Delegate="", Bundle="") // etc 

Cualquier ayuda en esto sería grande.

Gracias

+0

Esto podría etiquetarse mejor. Considere agregar 'objetivo-c',' iphone', etc. –

+0

Lo siento. Gracias por tu ayuda. – zardon

Respuesta

2

Esto es lo que escribí, cuando me enfermé de hacer lo mismo:

-(void)alert:(NSString *)title withBody:(NSString *)message firstButtonNamed:(NSString *)firstButtonName { 
    [self alert: title withBody: message firstButtonNamed: firstButtonName withExtraButtons: nil informing: nil]; 
} 

-(void)alert:(NSString *)title withBody:(NSString *)message firstButtonNamed:(NSString *)firstButtonName informing:(id)delegate { 
    [self alert: title withBody: message firstButtonNamed: firstButtonName withExtraButtons: nil informing: delegate]; 
} 

-(void)alert:(NSString *)title withBody:(NSString *)message firstButtonNamed:(NSString *)firstButtonName withExtraButtons:(NSArray *)otherButtonTitles informing:(id)delegate { 
    UIAlertView *alert = [[UIAlertView alloc] 
       initWithTitle: title 
       message: message 
       delegate: delegate 
       cancelButtonTitle: firstButtonName 
       otherButtonTitles: nil]; 
    if (otherButtonTitles != nil) { 
    for (int i = 0; i < [otherButtonTitles count]; i++) { 
     [alert addButtonWithTitle: (NSString *)[otherButtonTitles objectAtIndex: i]]; 
    } 
    } 
    [alert show]; 
    [alert release]; 
} 

No se puede escribir una función que mostrará una alerta y luego devolver un valor como una buttonIndex, porque ese retorno de valor solo ocurre cuando el usuario presiona un botón y su delegado hace algo.

En otras palabras, el proceso de hacer una pregunta con el UIAlertView es asincrónico.

+0

Oh, está bien. ¡Gracias por tu ayuda! – zardon

14

En 4.0+ puede simplificar el código de alerta utilizando bloques, un poco como esto:

CCAlertView *alert = [[CCAlertView alloc] 
    initWithTitle:@"Test Alert" 
    message:@"See if the thing works."]; 
[alert addButtonWithTitle:@"Foo" block:^{ NSLog(@"Foo"); }]; 
[alert addButtonWithTitle:@"Bar" block:^{ NSLog(@"Bar"); }]; 
[alert addButtonWithTitle:@"Cancel" block:NULL]; 
[alert show]; 

Ver Lambda Alert on GitHub.

+0

¡Gracias, lo necesitaba! –

+0

Solución muy resbaladiza. Funcionó muy bien para mí – Kongress

+0

¿Hay alguna forma de hacerlo sin usar la clase 'LambdaAlert'? – Chris