¿Qué código de inicio puedo usar para hacer un UIAlertView simple con un botón "OK" en él?Agregando un simple UIAlertView
Respuesta
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>
puede usar etiquetas si tiene más de 1 vista de alerta para determinar quién llamó al delegado. –
UIAlertView *alert = [[UIAlertView alloc]
initWithTitle:@"Title"
message:@"Message"
delegate:nil //or self
cancelButtonTitle:@"OK"
otherButtonTitles:nil];
[alert show];
[alert autorelease];
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.
UIAlertView *myAlert = [[UIAlertView alloc]
initWithTitle:@"Title"
message:@"Message"
delegate:self
cancelButtonTitle:@"Cancel"
otherButtonTitles:@"Ok",nil];
[myAlert show];
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];
}
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.
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
@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
Lo dije porque sé que no todos son expertos en comprender cada código y saber cómo reemplazarlo por uno funcional. – csharpwinphonexaml
This page muestra cómo agregar un UIAlertController si está utilizando Swift.
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.
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];
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)
- 1. agregando una biblioteca simple a un proyecto xcode 4
- 2. ¿Puedo mover un UIAlertView?
- 3. Rotar un UIAlertView
- 4. Agregar UIActivityindicatorView en un UIAlertView
- 5. UIAlertView Delegados
- 6. UIAlertView reemplazo
- 7. UIAlertView personalizado?
- 8. Personalización UIAlertView
- 9. UIAlertView cancelButtonTitle
- 10. Agregando clusterer de marcador simple al mapa de google
- 11. Agregando un SelectListItem predeterminado
- 12. UIAlertView evento Click en el interior UIAlertView delegado
- 13. Mostrar un UIAlertView en NSObject Clase
- 14. ¿Escribir una función para UIAlertView?
- 15. ¿Ocultar UIAlertView programmatically?
- 16. UIAlertView sin botón Cancelar?
- 17. UIView Popup como UIAlertView
- 18. UIAlertView: UIAlertViewStyleSecureTextInput: Teclado Numérico
- 19. iphone UIAlertView Modal
- 20. ¿Cómo funciona [UIAlertView show]?
- 21. impide que UIAlertView descarte
- 22. cancelar UIAlertView programación
- 23. Acción del botón UIAlertView?
- 24. Obtener texto de UIAlertView
- 25. otherButtonTitles en UIAlertView
- 26. ¿Cómo puedo descartar UIAlertView?
- 27. Mimic UIAlertView Bounce?
- 28. Agregando un ViewController a Appdelegate
- 29. Como puedo init un campo de texto en un UIAlertView
- 30. ¿Cómo agregar userInfo a UIAlertView?
¿Quieres que esperar para realizar una acción hasta que se hace clic en el botón OK? –
@sudo rm -rf: No, solo necesito que diga "Dee dee doo doo" o algo así. No se necesitan acciones – Linuxmint