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

Добавление простого UIAlertView

Что такое код стартера, который я мог бы использовать для создания простого UIAlertView с одной кнопкой "OK" на нем?

4b9b3361

Ответ 1

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

    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> 

Ответ 2

Другие ответы уже предоставляют информацию для 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/5:

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 (@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/5:

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)
    self.present(alertController, animated: true, completion: nil)
}
else {
    let alertView = UIAlertView(title: alertTitle, message: alertMessage, delegate: nil, cancelButtonTitle: nil, otherButtonTitles: alertOkButtonText)
    alertView.show()
}

UPD: обновлено для Swift 5. Заменена устаревшая проверка присутствия класса проверкой доступности в Obj-C.

Ответ 3

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

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

Ответ 4

UIAlertView *alert = [[UIAlertView alloc]
 initWithTitle:@"Title" 
 message:@"Message" 
 delegate:nil //or self
 cancelButtonTitle:@"OK"
 otherButtonTitles:nil];

 [alert show];
 [alert autorelease];

Ответ 5

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

Ответ 6

UIAlertView *myAlert = [[UIAlertView alloc] 
                         initWithTitle:@"Title"
                         message:@"Message"
                         delegate:self
                         cancelButtonTitle:@"Cancel"
                         otherButtonTitles:@"Ok",nil];
[myAlert show];

Ответ 7

Вот полный метод, который имеет только одну кнопку, "ok", чтобы закрыть 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];
}

Ответ 8

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

Ответ 9

Простое оповещение с данными массива:

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

Ответ 10

Для 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)