2011-07-29 9 views
12

Actualmente estoy usando el siguiente código para presentar un UIAlertView:hacer funcionar botón UIAlertView gatillo en la prensa de

UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Today's Entry Complete" 
         message:@"Press OK to submit your data!" 
         delegate:nil 
       cancelButtonTitle:@"OK" 
       otherButtonTitles: nil]; 
    [alert show]; 
    [alert release]; 

¿Cómo llego de modo que cuando 'OK" es presionado, se activa una función, por ejemplo -(void)submitData

Respuesta

41

NOTA:

Importante: UIAlertView está en desuso en iOS 8. (. Tenga en cuenta que UIAlertViewDelegate también está en desuso) para crear y administrar alertas en iOS 8 y versiones posteriores, en lugar de utilizar UIAlertController con un preferredStyle de UIAlertControllerStyleAlert.

Please check this out tutorial

"deprecated" means???

Objectvie C

archivo .h

@interface urViewController : UIViewController <UIAlertViewDelegate> { 

archivo .m

// Create Alert and set the delegate to listen events 
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Today's Entry Complete" 
               message:@"Press OK to submit your data!" 
               delegate:self 
             cancelButtonTitle:nil 
             otherButtonTitles:@"OK", nil]; 

// Set the tag to alert unique among the other alerts. 
// So that you can find out later, which alert we are handling 
alert.tag = 100; 

[alert show]; 


//[alert release]; 


-(void) alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{ 


    // Is this my Alert View? 
    if (alertView.tag == 100) { 
     //Yes 


    // You need to compare 'buttonIndex' & 0 to other value(1,2,3) if u have more buttons. 
    // Then u can check which button was pressed. 
     if (buttonIndex == 0) {// 1st Other Button 

      [self submitData]; 

     } 
     else if (buttonIndex == 1) {// 2nd Other Button 


     } 

    } 
    else { 
    //No 
     // Other Alert View 

    } 

} 

Swift

La forma Swifty es utilizar el nuevo UIAlertController y cierres:

// Create the alert controller 
    let alertController = UIAlertController(title: "Title", message: "Message", preferredStyle: .Alert) 

    // Create the actions 
    let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.Default) { 
     UIAlertAction in 
     NSLog("OK Pressed") 
    } 
    let cancelAction = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel) { 
     UIAlertAction in 
     NSLog("Cancel Pressed") 
    } 

    // Add the actions 
    alertController.addAction(okAction) 
    alertController.addAction(cancelAction) 

    // Present the controller 
    self.presentViewController(alertController, animated: true, completion: nil) 
1

Es necesario configurar el delegado en la asignación de la alertview, a continuación, utilice uno de los métodos UIAlertViewDelegate para llamar a su propio método, por ejemplo:

UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Today's Entry Complete" 
               message:@"Press OK to submit your data!" 
               delegate:self 
             cancelButtonTitle:@"OK" 
             otherButtonTitles:nil]; 
[alert show]; 
[alert release]; 

- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex 
{ 
    [self submitData]; 
} 
1

Necesita configurar el delegate para su UIAlertView, antes de mostrarlo. A continuación, hacer el trabajo en la devolución de llamada delegado tales como:

-(void)alertView:(UIAlertView*)alert didDismissWithButtonIndex:(NSInteger)buttonIndex; 
{ 
    if ([[alert buttonTitleAtIndex] isEqualToString:@"Do it"]) { 
     // Code to execute on Do it button selection. 
    } 
} 

Mi proyecto CWUIKit encima en https://github.com/Jayway/CWUIKit tiene una adición a UIAlertView que le permiten hacer lo mismo pero con bloques. Redusing la misma operación, tanto para crear, mostrar y manipular la alerta a esto:

[[UIAlertView alertViewWithTitle:@"My Title" 
         message:@"The Message" 
       cancelButtonTitle:@"Cancel" 
    otherTitlesAndAuxiliaryActions:@"Do it", 
           ^(CWAuxiliaryAction*a) { 
            // Code to execute on Do it button selection. 
           }, nil] show]; 
8

Si está utilizando varias instancias UIAlertView que no están declarados en la interfaz de la clase también se puede establecer una etiqueta para identificar los casos en los que su delegado método, por ejemplo:

en algún lugar encima de su archivo de clase myClass.m

#define myAlertViewsTag 0 

crear el UIAlertView:

UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"My Alert" 
    message:@"please press ok or cancel" 
    delegate:self 
    cancelButtonTitle:@"Cancel" 
    otherButtonTitles:@"OK", nil]; 
alert.tag = myAlertViewsTag; 
[alert show]; 
[alert release]; 

el método delegado:

-(void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex { 
    if (alertView.tag == myAlertViewsTag) { 
     if (buttonIndex == 0) { 
      // Do something when cancel pressed 
     } else { 
      // Do something for ok 
     } 
    } else { 
     // Do something with responses from other alertViews 
    } 
} 
0

Si desea utilizar bloques también se puede utilizar MKAdditions para lograr esto fácilmente incluso para múltiples UIAlertViews.

sólo tiene que utilizar un código similar a este ejemplo:

[[UIAlertView alertViewWithTitle:@"Test" 
         message:@"Hello World" 
       cancelButtonTitle:@"Dismiss" 
       otherButtonTitles:[NSArray arrayWithObjects:@"First", @"Second", nil] 
         onDismiss:^(int buttonIndex) 
{ 
    NSLog(@"%d", buttonIndex); 
} 
onCancel:^() 
{ 
    NSLog(@"Cancelled");   
} 
] show]; 

Puede encontrar más información en este tutorial: http://blog.mugunthkumar.com/coding/ios-code-block-based-uialertview-and-uiactionsheet

0

Poco más aclaraciones,

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex 
    { 
     //handles title you've added for cancelButtonTitle 
     if(buttonIndex == [alertView cancelButtonIndex]) { 
      //do stuff 
     }else{ 
      //handles titles you've added for otherButtonTitles 
      if(buttonIndex == 1) { 
       // do something else 
      } 
      else if(buttonIndex == 2) { 
       // do different thing 
      } 
     } 
    } 

ejemplo,

UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Need your action!" 
message:@"Choose an option to continue!" delegate:self cancelButtonTitle:@"Not Need!" 
otherButtonTitles:@"Do Something", @"Do Different", nil]; 
[alert show]; 

enter image description here

(Es iOS7 pantalla)

0

De iOS8 de Apple proporciona nueva clase UIAlertController que se puede utilizar en lugar de UIAlertView que ahora está en desuso, su también se afirma en el mensaje depreciación

UIAlertView es obsoleto. Utilice UIAlertController con un preferredStyle de UIAlertControllerStyleAlert lugar

por lo que debe usar algo como esto

Objective C

UIAlertController * alert = [UIAlertController 
       alertControllerWithTitle:@"Title" 
           message:@"Message" 
          preferredStyle:UIAlertControllerStyleAlert]; 

    UIAlertAction* yesButton = [UIAlertAction 
         actionWithTitle:@"Yes, please" 
            style:UIAlertActionStyleDefault 
           handler:^(UIAlertAction * action) { 
            //Handle your yes please button action here 
           }]; 

    UIAlertAction* noButton = [UIAlertAction 
          actionWithTitle:@"No, thanks" 
             style:UIAlertActionStyleDefault 
            handler:^(UIAlertAction * action) { 
             //Handle no, thanks button     
            }]; 

    [alert addAction:yesButton]; 
    [alert addAction:noButton]; 

    [self presentViewController:alert animated:YES completion:nil]; 

Swift

La forma más fácil es usar el nuevo UIAlertController y cierres:

// Create the alert controller 
    let alertController = UIAlertController(title: "Title", message: "Message", preferredStyle: .Alert) 

    // Create the actions 
    let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.Default) { 
     UIAlertAction in 
     NSLog("OK Pressed") 
    } 
    let cancelAction = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel) { 
     UIAlertAction in 
     NSLog("Cancel Pressed") 
    } 

    // Add the actions 
    alertController.addAction(okAction) 
    alertController.addAction(cancelAction) 

    // Present the controller 
    self.presentViewController(alertController, animated: true, completion: nil) 
Cuestiones relacionadas