开发者

Make UIAlertView Button trigger function On Press

开发者 https://www.devze.com 2023-03-24 00:54 出处:网络
Currently I am using the following code to present a UIAlertView: UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@\"Today\'s Entry Complete\"

Currently I am using the following code to present a UIAlertView:

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

How do I get it so that when 'OK" is pressed, it triggers a function, say -(void)submitData


NOTE:

Important: UIAlertView is deprecated in iOS 8. (Note that UIAlertViewDelegate is also deprecated.) To create and manage alerts in iOS 8 and later, instead use UIAlertController with a preferredStyle of UIAlertControllerStyleAlert.

Please check this out tutorial

"deprecated" means???

Objectvie C

.h file

    @interface urViewController : UIViewController <UIAlertViewDelegate> {

.m file

// 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

The Swifty way is to use the new UIAlertController and closures:

    // 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)


If you are using multiple UIAlertView instances that are not declared in the class's interface you can also set a tag to identify instances in your delegate method, for example:

somewhere on top of your class file myClass.m

#define myAlertViewsTag 0

creating the 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];

the delegate method:

-(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
    }
}


You need to set the delegate when allocating the alertview, then use one of the UIAlertViewDelegate methods to call your own method, for example:

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];
}


You need to setup the delegate for your UIAlertView, before showing it. Then do the work in the delegate callback as such:

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

My CWUIKit project over at https://github.com/Jayway/CWUIKit has an addition to UIAlertView that allow you to do the same thing but with blocks. Redusing the same operation for both creating, showing and handling the alert to this:

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


If you want to use blocks you can also use MKAdditions to achieve this easily even for multiple UIAlertViews.

Just use a code similar to this sample:

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

You can find more information in this tutorial: http://blog.mugunthkumar.com/coding/ios-code-block-based-uialertview-and-uiactionsheet


Little more clarification,

- (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
            }
        }
    }

Example,

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];

Make UIAlertView Button trigger function On Press

(it's iOS7 screenshot)


From iOS8 Apple provide new UIAlertController class which you can use instead of UIAlertView which is now deprecated, its is also stated in depreciation message

UIAlertView is deprecated. Use UIAlertController with a preferredStyle of UIAlertControllerStyleAlert instead

So you should use something like this

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

The Swifty way is to use the new UIAlertController and closures:

    // 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)
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号