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

时间:2013-08-23 13:30:57

标签: ios objective-c button uialertview

我有一个带有2个按钮的重新加载按钮的UIAlertView - 确定和取消。取消按钮工作正常,但当我想在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");
    }

}

是的,我已将UIAlertViewDelegate协议放入h中。文件

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

1 个答案:

答案 0 :(得分:5)

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

- (void)reloadGame {}

方法并手动重置所有内容。类似的东西:

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

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

- (void)viewDidLoad {
[super viewDidLoad];
[self reloadGame];
}

而不是为同一个类提供2个.m文件: 你应该让你的popOver类不同,并将它的委托设置为你的游戏类:

你应该在你的popOver课程中

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

@interface  CustomPopoverView : UIView
@property (nonatomic, retain) id <CustomPopoverView> delegate;

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

//popover init/alloc 
popover.delegate = self; 
//show popover

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

#import "CustomPopoverView.h"
@interface GameViewClass : UIViewController <CustomPopoverViewDelegate>

并在你想要转发到游戏类的方法的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];
}
}

和你将放置的gameClass

- (void)doSomething {
//whatever 
}

你也可以发送参数


你也可以继承...(当然popover是另一个拥有它的类.h)

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

enter image description here

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

@interface  CustomPopoverView : GameView

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

相关问题