Добавление простого UIAlertView - PullRequest
103 голосов
/ 16 декабря 2010

Какой начальный код я мог бы использовать для создания простого UIAlertView с одной кнопкой «ОК»?

Ответы [ 10 ]

227 голосов
/ 16 декабря 2010

Если вы хотите, чтобы показывалось оповещение, сделайте следующее:

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

Если вы хотите что-то сделать при нажатии кнопки, реализуйте этот метод делегата:

- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex {
    // the user clicked OK
    if (buttonIndex == 0) {
        // do something here...
    }
}

И убедитесь, что ваш делегат соответствует протоколу UIAlertViewDelegate:

@interface YourViewController : UIViewController <UIAlertViewDelegate> 
67 голосов
/ 07 февраля 2015

Другие ответы уже предоставляют информацию для iOS 7 и старше, однако UIAlertView устарела в iOS 8 .

В iOS 8+ вы должны использовать UIAlertController. Это замена для UIAlertView и UIActionSheet. Документация: Справочник по классам UIAlertController . И хорошая статья о NSHipster .

Чтобы создать простое представление оповещений, вы можете сделать следующее:

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)

Обратите внимание, что, поскольку он был добавлен в iOS 8, этот код не будет работать на iOS 7 и старше. Так что, к сожалению, сейчас мы должны использовать проверку версий следующим образом:

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+
// Starting with Xcode 9, you can also use 
// if (@available(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: обновлено для Swift 3 / 4.

UPD 2: добавлена ​​заметка для @available в Objc-C, начиная с Xcode 9.

11 голосов
/ 21 ноября 2015

UIAlertView устарела на iOS 8. Поэтому, чтобы создать предупреждение на iOS 8 и выше, рекомендуется использовать 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];

Вот как я это реализовал.

9 голосов
/ 29 мая 2013
UIAlertView *myAlert = [[UIAlertView alloc] 
                         initWithTitle:@"Title"
                         message:@"Message"
                         delegate:self
                         cancelButtonTitle:@"Cancel"
                         otherButtonTitles:@"Ok",nil];
[myAlert show];
9 голосов
/ 17 декабря 2010

В качестве дополнения к двум предыдущим ответам (пользователя "sudo rm -rf" и "Evan Mulawski"), если вы не хотите ничего делать при щелчке по представлению предупреждений, вы можете просто выделить, показать иотпустите это.Вам не нужно объявлять протокол делегата.

9 голосов
/ 16 декабря 2010
UIAlertView *alert = [[UIAlertView alloc]
 initWithTitle:@"Title" 
 message:@"Message" 
 delegate:nil //or self
 cancelButtonTitle:@"OK"
 otherButtonTitles:nil];

 [alert show];
 [alert autorelease];
3 голосов
/ 10 марта 2014

Вот полный метод, который имеет только одну кнопку «ОК» для закрытия 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];
}
1 голос
/ 06 августа 2015

На этой странице показано, как добавить UIAlertController, если вы используете Swift.

0 голосов
/ 19 января 2017

Для 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)
0 голосов
/ 17 марта 2016

Простое предупреждение с массивом данных:

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