Как создать окно оповещения в iphone? - PullRequest
28 голосов
/ 03 мая 2011

Я хотел бы создать поле типа предупреждения, чтобы, когда пользователь пытается что-то удалить, оно сообщало: «Вы уверены», а затем указывало «да» или «нет», если они уверены.Что было бы лучшим способом сделать это в iphone?

Ответы [ 10 ]

60 голосов
/ 03 мая 2011

A UIAlertView - лучший способ сделать это.Он оживит середину экрана, затемнит фон и заставит пользователя обратиться к нему, прежде чем вернуться к обычным функциям вашего приложения.

Вы можете создать UIAlertView, например:

UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Wait" message:@"Are you sure you want to delete this.  This action cannot be undone" delegate:self cancelButtonTitle:@"Delete" otherButtonTitles:@"Cancel", nil];
[alert show];

Это будет отображать сообщение.

Затем, чтобы проверить, нажали ли они удалить или отменить, используйте это:

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (buttonIndex == 0){
        //delete it
    }
}

Убедитесь, что в вашем файле заголовка (.h), вы включаете UIAlertViewDelegate, помещая <UIAlertViewDelegate> рядом с тем, что наследует ваш класс (т. е. UIViewController или UITableViewController и т. д.)

Для получения дополнительной информации обо всех особенностяхUIAlertViews проверить Документы Apple здесь

Надеюсь, что поможет

14 голосов
/ 08 января 2015

Пост довольно старый, но все же хороший вопрос. С iOS 8 ответ изменился. Сегодня вы бы предпочли использовать UIAlertController с предпочтительным стилем UIAlertControllerStyle.ActionSheet.

Код, подобный этому (быстрый), связанный с кнопкой:

@IBAction func resetClicked(sender: AnyObject) {
    let alert = UIAlertController(
        title: "Reset GameCenter Achievements",
        message: "Highscores and the Leaderboard are not affected.\nCannot be undone",
        preferredStyle: UIAlertControllerStyle.ActionSheet)
    alert.addAction(
        UIAlertAction(
            title: "Reset Achievements",
            style: UIAlertActionStyle.Destructive,
            handler: {
                (action: UIAlertAction!) -> Void in
                gameCenter.resetAchievements()
            }
        )
    )
    alert.addAction(
        UIAlertAction(
            title: "Show GameCenter",
            style: UIAlertActionStyle.Default,
            handler: {
                (action: UIAlertAction!) -> Void in
                self.gameCenterButtonClicked()
            }
        )
    )
    alert.addAction(
        UIAlertAction(
            title: "Cancel",
            style: UIAlertActionStyle.Cancel,
            handler: nil
        )
    )
    if let popoverController = alert.popoverPresentationController {
        popoverController.sourceView = sender as UIView
        popoverController.sourceRect = sender.bounds
    }
    self.presentViewController(alert, animated: true, completion: nil)
}

выдаст такой вывод: enter image description here

РЕДАКТИРОВАТЬ: код сбоя на iPad, iOS 8+. Если добавлены необходимые строки, как описано здесь: в другом ответе переполнения стека

2 голосов
/ 09 октября 2016

Для Свифта это очень просто.

    //Creating the alert controller
    //It takes the title and the alert message and prefferred style
    let alertController = UIAlertController(title: "Hello  Coders", message: "Visit www.simplifiedios.net to learn xcode", preferredStyle: .Alert)

    //then we create a default action for the alert... 
    //It is actually a button and we have given the button text style and handler
    //currently handler is nil as we are not specifying any handler
    let defaultAction = UIAlertAction(title: "Close Alert", style: .Default, handler: nil)

    //now we are adding the default action to our alertcontroller
    alertController.addAction(defaultAction)

    //and finally presenting our alert using this method
    presentViewController(alertController, animated: true, completion: nil)

Ссылка: iOS Показать предупреждающее сообщение

1 голос
/ 03 мая 2011

Все говорят UIAlertView.Но чтобы подтвердить удаление, UIActionSheet, вероятно, является лучшим выбором.См. Когда использовать UIAlertView против UIActionSheet

0 голосов
/ 18 мая 2018

Здесь я предоставил предупреждающее сообщение, которое я использовал в моем первом приложении:

@IBAction func showMessage(sender: UIButton) {
    let alertController = UIAlertController(title: "Welcome to My First App",
                              message: "Hello World",
                              preferredStyle: UIAlertControllerStyle.alert)
    alertController.addAction(UIAlertAction(title: "OK",
                                            style: UIAlertActionStyle.default,
                                            handler: nil))
    present(alertController, animated: true, completion: nil)
}

с соответствующими обработчиками для пользовательских ответов.

0 голосов
/ 28 апреля 2018

Поскольку UIAlertView устарело, я хотел дать ответ будущим кодировщикам, которые сталкиваются с этим.

Вместо UIAlertView я бы использовал UIAlertController примерно так:

@IBAction func showAlert(_ sender: Any) {
  let alert = UIAlertController(title: "My Alert", message: "This is my alert", preferredStyle: UIAlertControllerStyle.alert)

  alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.default, handler: {(action) in 
    alert.dismiss(animated: true, completion: nil)
  }))
  self.present(alert,animated:true, completion:nil)
}
0 голосов
/ 03 мая 2011

Для вывода сообщения с предупреждением используйте UIAlertView.

 UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Wait" message:@"Are you sure you want to delete this." **delegate:self** cancelButtonTitle:@"Delete" otherButtonTitles:@"Cancel", nil];
[alert show];
[alert release];

Как только вы установите делегата как самого себя, вы можете выполнить свое действие с этим методом

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
0 голосов
/ 03 мая 2011

Использовать UIAlertView :

UIAlertView *av = [[UIAlertView alloc] initWithTitle:@"Alert Title" 
                                                     message:@"are you sure?"
                                                    delegate:self 
                                           cancelButtonTitle:@"No"
                                           otherButtonTitles:@"Yes", nil];


        [av show];
        [av autorelease];

Убедитесь, что вы внедрили:

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex

Для обработки ответа.

0 голосов
/ 03 мая 2011

Используйте UIAlertView class для отображения предупреждающего сообщения пользователю.

0 голосов
/ 03 мая 2011

UIAlertView кажется очевидным выбором для подтверждения.

Установить делегата на контроллер и реализовать протокол UIAlertViewDelegate http://developer.apple.com/library/ios/#documentation/uikit/reference/UIAlertViewDelegate_Protocol/UIAlertViewDelegate/UIAlertViewDelegate.html

...