Подтвердить что ты не робот

Сделать триггерную функцию кнопки UIAlertView On Press

В настоящее время я использую следующий код для представления UIAlertView:

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

Как мне получить, чтобы при нажатии "ОК" она запускает функцию, например -(void)submitData

4b9b3361

Ответ 1

Примечание:

Важно: UIAlertView устарел в iOS 8. (Обратите внимание, что UIAlertViewDelegate также устарел.) Чтобы создавать и управлять предупреждениями в iOS 8 и более поздних версиях, вместо этого используйте UIAlertController с предпочтительнымStyle из UIAlertControllerStyleAlert.

Пожалуйста, ознакомьтесь с этим учебным пособием

"устаревший" означает???

Objectvie C

.h файл

    @interface urViewController : UIViewController <UIAlertViewDelegate> {

.m file

// Create Alert and set the delegate to listen events
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Today 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

    }

}

Свифта

Swifty способ использовать новый UIAlertController и закрытия:

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

Ответ 2

Если вы используете несколько экземпляров UIAlertView, которые не объявлены в интерфейсе класса, вы также можете установить тег для идентификации экземпляров в методе делегата, например:

где-то поверх вашего файла класса myClass.m

#define myAlertViewsTag 0

создание 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];

метод делегата:

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

Ответ 3

Вам нужно установить делегат при распределении предупреждения, а затем использовать один из методов UIAlertViewDelegate для вызова своего собственного метода, например:

UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Today 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];
}

Ответ 4

Вам нужно настроить delegate для вашего UIAlertView, прежде чем показывать его. Затем выполните работу в обратном вызове делегата как таковой:

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

Мой проект CWUIKit над https://github.com/Jayway/CWUIKit имеет дополнение к UIAlertView, которое позволяет вам делать то же самое, но с блоками. Повторное использование той же операции для создания, отображения и обработки предупреждения:

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

Ответ 5

Если вы хотите использовать блоки, вы также можете использовать MKAdditions, чтобы достичь этого легко даже для нескольких UIAlertViews.

Просто используйте код, похожий на этот пример:

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

Дополнительную информацию вы можете найти в этом уроке: http://blog.mugunthkumar.com/coding/ios-code-block-based-uialertview-and-uiactionsheet

Ответ 6

Немного больше разъяснений,

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

Пример

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

(снимок экрана iOS7)

Ответ 7

Из iOS8 Apple предоставляет новый класс UIAlertController, который вы можете использовать вместо UIAlertView, который теперь устарел, его также указывается в сообщении об амортизации

UIAlertView устарел. Использовать UIAlertController с предпочтительнымStyle вместо UIAlertControllerStyleAlert

Итак, вы должны использовать что-то вроде этого

Цель 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];

Свифта

Swifty способ использовать новый UIAlertController и закрытия:

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