Я хотел бы создать окно типа предупреждения, чтобы, когда пользователь пытается что-то удалить, он говорит: "Вы уверены", а затем да или нет, если они уверены. Какой был бы лучший способ сделать это в iphone?
Как создать окно оповещения в iphone?
Ответ 1
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 здесь
Надеюсь, что поможет
Ответ 2
Сообщение довольно старое, но все еще хороший вопрос. С iOS 8 ответ изменился. Сегодня вы предпочитаете использовать "UIAlertController" с "preferredStyle" в "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)
}
будет производить этот вывод:
EDIT: код разбился на iPad, iOS 8+. Если добавлены необходимые строки, как описано здесь: в другом ответе
Ответ 3
Для быстрого очень просто.
//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 Show Alert Message
Ответ 4
Все говорят UIAlertView. Но для подтверждения удаления, UIActionSheet, вероятно, лучший выбор. См. Когда использовать UIAlertView или UIActionSheet
Ответ 5
UIAlertView кажется очевидным выбором для подтверждения.
Установите делегата в контроллер и реализуйте протокол UIAlertViewDelegate http://developer.apple.com/library/ios/#documentation/uikit/reference/UIAlertViewDelegate_Protocol/UIAlertViewDelegate/UIAlertViewDelegate.html
Ответ 6
Используйте класс UIAlertView, чтобы отобразить пользователю предупреждение.
Ответ 7
Используйте 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
Чтобы обработать ответ.
Ответ 8
Чтобы вывести сообщение оповещения, используйте 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];
После того как вы установите делегата как self, вы можете выполнить свое действие по этому методу
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex