Включение функции запуска кнопки UIAlertView при нажатии
В настоящее время я использую следующий код для представления UIAlertView:
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Today's Entry Complete"
message:@"Press OK to submit your data!"
delegate:nil
cancelButtonTitle:@"OK"
otherButtonTitles: nil];
[alert show];
[alert release];
Как сделать так, чтобы при нажатии "ОК" запускалась функция, скажем -(void)submitData
7 ответов
НОТА:
Важное замечание : UIAlertView устарела в iOS 8. (Обратите внимание, что UIAlertViewDelegate также устарела.) Для создания и управления оповещениями в iOS 8 и более поздних версиях вместо этого используйте UIAlertController с предпочитаемым стилем UIAlertControllerStyleAlert.
Пожалуйста, проверьте это руководство
"не рекомендуется" означает???
Objectvie C
.h файл
@interface urViewController : UIViewController <UIAlertViewDelegate> {
.m файл
// Create Alert and set the delegate to listen events
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Today's 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)
Если вы используете несколько экземпляров 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
}
}
Вам нужно установить делегат при выделении alertview, а затем использовать один из методов UIAlertViewDelegate для вызова вашего собственного метода, например:
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Today's 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];
}
Вам необходимо настроить 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];
Если вы хотите использовать блоки, вы также можете использовать 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
Немного больше разъяснений,
- (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];
(это скриншот iOS7)
От iOS8 Apple предоставит новый UIAlertController
класс, который вы можете использовать вместо UIAlertView, который теперь устарел, его также указывается в сообщении об устаревании
UIAlertView устарела. Вместо этого используйте UIAlertController с предпочитаемым стилем UIAlertControllerStyleAlert
Так что вы должны использовать что-то вроде этого
Цель С
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)