如何在UIAlertView的按钮中执行操作?

1 objective-c button uialertview ios

我有一个UIAlertView带有2个按钮的重新加载按钮 - 确定和取消.取消按钮工作正常,但是当我想要一些动作(再次玩游戏)OK按钮不起作用,除非该动作是一个NSLog.

我的代码是m.文件:

- (IBAction)startAgainAction:(id)sender {

    UIAlertView *alert = [[UIAlertView alloc] 
                         initWithTitle:@"Warning" message:@"Have you short that want start again the game?" 
                         delegate:self 
                         cancelButtonTitle:@"OK" 
                         otherButtonTitles:@"Cancel", nil];

    [alert show];
}

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

    // My OK button

    if (buttonIndex == alertView.cancelButtonIndex) {

        // Action to start the game again... (don't work)
        [self viewDidLoad];

    } else if (buttonIndex == alertView.firstOtherButtonIndex) {

        // NSLog it's accept but not other actions...
        NSLog(@"Cancel");
    }

}
Run Code Online (Sandbox Code Playgroud)

是的,我把UIAlertViewDelegate协议放在了h.文件

那么,为什么viewDidLoad当它再次调用该方法时不起作用?

Ton*_*min 5

为了重新加载...你应该做一个

- (void)reloadGame {}
Run Code Online (Sandbox Code Playgroud)

方法并手动重置所有内容.就像是:

- (void)reloadGame {
self.highScore = 0; 
self.ballPosition = ... 
// etc. depends on what you have
}
Run Code Online (Sandbox Code Playgroud)

您还可以定义一些常量,这样您就不会对所有内容进行硬编码.并在ViewDidLoad和reloadGame中提供它们......或者更好...将viewDidLoad中的所有代码移动到reloadGame中并将其更改为:

- (void)viewDidLoad {
[super viewDidLoad];
[self reloadGame];
}
Run Code Online (Sandbox Code Playgroud)

而不是为同一个类提供2个.m文件:您应该将您的popOver类设置为另一个并将其委托给您的游戏类:

在你的popOver类中你应该这样做:

@protocol CustomPopoverViewDelegate <NSObject>
- (void)doSomething;
// add other methods you need 
@end

@interface  CustomPopoverView : UIView
@property (nonatomic, retain) id <CustomPopoverView> delegate;
Run Code Online (Sandbox Code Playgroud)

当你在游戏类中打开popOver时,你应该添加:

//popover init/alloc 
popover.delegate = self; 
//show popover
Run Code Online (Sandbox Code Playgroud)

还要确保你的游戏类监听popover委托方法

#import "CustomPopoverView.h"
@interface GameViewClass : UIViewController <CustomPopoverViewDelegate>
Run Code Online (Sandbox Code Playgroud)

并且在你想要转发到你刚刚放置的游戏类的方法中的customPopover类中

- (void)methodNameForDoSomething {
if ([self.delegate respondsToSelector:@selector(doSomething)]) {   //always nice to check. Notice this is the same doSomething we declared in .h in the protocol 
    [self.delegate doSomething];
}
}
Run Code Online (Sandbox Code Playgroud)

和你将放的gameClass

- (void)doSomething {
//whatever 
}
Run Code Online (Sandbox Code Playgroud)

你也可以发送参数


你也可以子类...(当然popover是另一个有它自己的类.h)

并将其声明为子类(您可以在创建新类时执行此操作并输入要子类化的类名,如下图所示)

在此输入图像描述

并且你的popover视图的标题将是:

@interface  CustomPopoverView : GameView
Run Code Online (Sandbox Code Playgroud)

并将拥有GameView的所有方法和属性.