Make UIAlertView Button trigger function On Press

后端 未结 7 2065
小蘑菇
小蘑菇 2020-12-25 09:22

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

UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@\"Today\'s Entry Complete\"
               


        
7条回答
  •  情书的邮戳
    2020-12-25 09:42

    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)
    

提交回复
热议问题