2010-12-16 6 views
97

¿Qué código de inicio puedo usar para hacer un UIAlertView simple con un botón "OK" en él?Agregando un simple UIAlertView

+0

¿Quieres que esperar para realizar una acción hasta que se hace clic en el botón OK? –

+1

@sudo rm -rf: No, solo necesito que diga "Dee dee doo doo" o algo así. No se necesitan acciones – Linuxmint

Respuesta

218

Cuando desea que la alerta para mostrar, hacer esto:

UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"ROFL" 
                message:@"Dee dee doo doo." 
                delegate:self 
                cancelButtonTitle:@"OK" 
                otherButtonTitles:nil]; 
[alert show]; 

    // If you're not using ARC, you will need to release the alert view. 
    // [alert release]; 

Si usted quiere hacer algo cuando se hace clic en el botón, poner en práctica este método delegado:

- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex { 
    // the user clicked OK 
    if (buttonIndex == 0) { 
     // do something here... 
    } 
} 

Y asegúrese de que su delegado cumpla con el protocolo UIAlertViewDelegate:

@interface YourViewController : UIViewController <UIAlertViewDelegate> 
+4

puede usar etiquetas si tiene más de 1 vista de alerta para determinar quién llamó al delegado. –

9
UIAlertView *alert = [[UIAlertView alloc] 
initWithTitle:@"Title" 
message:@"Message" 
delegate:nil //or self 
cancelButtonTitle:@"OK" 
otherButtonTitles:nil]; 

[alert show]; 
[alert autorelease]; 
9

Como complemento a las dos respuestas anteriores (del usuario "sudo rm -rf" y "Evan Mulawski"), si no desea hacer nada cuando se hace clic en su vista de alerta, puede asignar, mostrar y liberarlo. No tiene que declarar el protocolo de delegado.

9
UIAlertView *myAlert = [[UIAlertView alloc] 
         initWithTitle:@"Title" 
         message:@"Message" 
         delegate:self 
         cancelButtonTitle:@"Cancel" 
         otherButtonTitles:@"Ok",nil]; 
[myAlert show]; 
3

Aquí es un método completo que sólo tiene un botón, un 'ok', para cerrar la UIAlert:

- (void) myAlert: (NSString*)errorMessage 
{ 
    UIAlertView *myAlert = [[UIAlertView alloc] 
          initWithTitle:errorMessage 
          message:@"" 
          delegate:self 
          cancelButtonTitle:nil 
          otherButtonTitles:@"ok", nil]; 
    myAlert.cancelButtonIndex = -1; 
    [myAlert setTag:1000]; 
    [myAlert show]; 
} 
57

Otras respuestas ya proporcionan información para iOS 7 y mayores, sin embargo UIAlertView es obsoleto en iOS 8.

En iOS 8+ debe usar UIAlertController. Es un reemplazo para UIAlertView y UIActionSheet. Documentación: UIAlertController Class Reference. Y un buen artículo en NSHipster.

Para crear un simple Vista de alertas que puede hacer lo siguiente:

UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"Title" 
                     message:@"Message" 
                    preferredStyle:UIAlertControllerStyleAlert]; 
//We add buttons to the alert controller by creating UIAlertActions: 
UIAlertAction *actionOk = [UIAlertAction actionWithTitle:@"Ok" 
                style:UIAlertActionStyleDefault 
               handler:nil]; //You can use a block here to handle a press on this button 
[alertController addAction:actionOk]; 
[self presentViewController:alertController animated:YES completion:nil]; 

Swift 3/4:

let alertController = UIAlertController(title: "Title", message: "Message", preferredStyle: .alert) 
//We add buttons to the alert controller by creating UIAlertActions: 
let actionOk = UIAlertAction(title: "OK", 
    style: .default, 
    handler: nil) //You can use a block here to handle a press on this button 

alertController.addAction(actionOk) 

self.present(alertController, animated: true, completion: nil) 

Tenga en cuenta, que, desde que se añadió en iOS 8, esta el código no funcionará en iOS 7 y anteriores. Así que, por desgracia, por ahora tenemos que utilizar comprobaciones de versión de esta manera:

NSString *alertTitle = @"Title"; 
NSString *alertMessage = @"Message"; 
NSString *alertOkButtonText = @"Ok"; 

if ([UIAlertController class] == nil) { //[UIAlertController class] returns nil on iOS 7 and older. You can use whatever method you want to check that the system version is iOS 8+ 
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:alertTitle 
                 message:alertMessage 
                 delegate:nil 
               cancelButtonTitle:nil 
               otherButtonTitles:alertOkButtonText, nil]; 
    [alertView show]; 
} 
else { 
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:alertTitle 
                      message:alertMessage 
                     preferredStyle:UIAlertControllerStyleAlert]; 
    //We add buttons to the alert controller by creating UIAlertActions: 
    UIAlertAction *actionOk = [UIAlertAction actionWithTitle:alertOkButtonText 
                 style:UIAlertActionStyleDefault 
                handler:nil]; //You can use a block here to handle a press on this button 
    [alertController addAction:actionOk]; 
    [self presentViewController:alertController animated:YES completion:nil]; 
} 

Swift 3/4:

let alertTitle = "Title" 
let alertMessage = "Message" 
let alertOkButtonText = "Ok" 

if #available(iOS 8, *) { 
    let alertController = UIAlertController(title: alertTitle, message: alertMessage, preferredStyle: .alert) 
    //We add buttons to the alert controller by creating UIAlertActions: 
    let actionOk = UIAlertAction(title: alertOkButtonText, 
     style: .default, 
     handler: nil) //You can use a block here to handle a press on this button 

    alertController.addAction(actionOk) 
} 
else { 
    let alertView = UIAlertView(title: alertTitle, message: alertMessage, delegate: nil, cancelButtonTitle: nil, otherButtonTitles: alertOkButtonText) 
    alertView.show() 
} 

UPD: actualizado para Swift 3/4.

+1

No debe publicar código que podría funcionar pero no lo hace. En lugar de usar MyOwnUtilsClass, solo escriba el código que verifica la versión de ios. – csharpwinphonexaml

+1

@csharpwinphonexaml, no estoy de acuerdo. Sería una complicación innecesaria del código. La versión actual ilustra el uso de UIAlerView/UIAlertController, mientras que la verificación de la versión del sistema no es el tema de esta pregunta. En Swift hay un método integrado de una línea para verificar la versión del sistema operativo, así que lo usé. Objective-C tiene varios métodos, pero ninguno de ellos es elegante. – FreeNickname

+1

Lo dije porque sé que no todos son expertos en comprender cada código y saber cómo reemplazarlo por uno funcional. – csharpwinphonexaml

1

This page muestra cómo agregar un UIAlertController si está utilizando Swift.

9

UIAlertView está en desuso en iOS 8. Por lo tanto, crear una alerta en iOS 8 y superior, se recomienda utilizar UIAlertController:

UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Title" message:@"Alert Message" preferredStyle:UIAlertControllerStyleAlert]; 
UIAlertAction *defaultAction = [UIAlertAction actionWithTitle:@"Ok" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action){ 

    // Enter code here 
}]; 
[alert addAction:defaultAction]; 

// Present action where needed 
[self presentViewController:alert animated:YES completion:nil]; 

Esta es la forma en que he puesto en práctica.

0

alerta simple con datos de la matriz:

NSString *name = [[YourArray objectAtIndex:indexPath.row ]valueForKey:@"Name"]; 

NSString *msg = [[YourArray objectAtIndex:indexPath.row ]valueForKey:@"message"]; 

UIAlertView *alert = [[UIAlertView alloc] initWithTitle:name 
               message:msg 
               delegate:self 
             cancelButtonTitle:@"OK" 
             otherButtonTitles:nil]; 
[alert show]; 
-1

Para Swift 3:

let alert = UIAlertController(title: "Alert", message: "Message", preferredStyle: UIAlertControllerStyle.alert) 
alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil)) 
self.present(alert, animated: true, completion: nil)