xcode 按钮上的 iOS 警报视图操作
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14664679/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
iOS alertview action on a button
提问by Stumpp
I have a button in a menu which when touched, pops up a alert message with two buttons: "Cancel
" and "Yes
". This is the code I have for the alert:
我在菜单中有一个按钮,当触摸该按钮时,会弹出一条带有两个按钮的警报消息:“ Cancel
”和“ Yes
”。这是我的警报代码:
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Exit game"
message:@"Are you sure?"
delegate:nil
cancelButtonTitle:@"Cancel"
otherButtonTitles:@"Yes", nil];
[alert show];
Is it possible to add an action to the button "Yes
"?
是否可以向按钮“ Yes
”添加操作?
回答by Saurabh Shukla
In your code set the UIAlertView delegate:
在您的代码中设置 UIAlertView 委托:
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Exit game" message:@"Are you sure?" delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"Yes", nil]; [alert show];
As you have set delegate to self, write the delegate function in the same class as shown below:
由于您已将委托设置为 self,请在同一个类中编写委托函数,如下所示:
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
if (buttonIndex == 1) { // Set buttonIndex == 0 to handel "Ok"/"Yes" button response
// Cancel button response
}}
回答by Jason Pawlak
You need to implement the UIAlertViewDelegate
你需要实现 UIAlertViewDelegate
and add the following...
并添加以下内容...
- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex {
if (buttonIndex == 1) {
// do stuff
}
}
回答by Ray Fix
Yes it is easy. See that argument called "delegate" that you have set to nil right now? Set that to an object... usually "self" if you are calling it from your view controller and then implement the selector for UIAlertViewDelegate.
是的,这很容易。看到您现在设置为 nil 的名为“delegate”的参数了吗?将它设置为一个对象...通常是“self”,如果你从你的视图控制器调用它,然后实现 UIAlertViewDelegate 的选择器。
You also need to declare that your view controller conforms to the UIAlertViewDelegate protocol. A good place to do this is in the "private" continuation class of the view controller.
您还需要声明您的视图控制器符合 UIAlertViewDelegate 协议。这样做的一个好地方是在视图控制器的“私有”延续类中。
@interface MyViewController() <UIAlertViewDelegate>
@end
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
NSLog(@"Button pushed: %d", buttonIndex);
}