簡體   English   中英

如何在UIAlertView的按鈕中執行操作?

[英]How can I do actions in buttons of a UIAlertView?

我有一個帶有2個按鈕的重新加載按鈕的UIAlertView確定和取消。 取消按鈕可以正常工作,但是當我要在確定按鈕中進行一些操作(再次玩游戲)時,除非該操作為NSLog否則該按鈕將不起作用。

我在米中的代碼 文件:

- (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不起作用?

要重新加載...,您應該

- (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的另一個類)

並將其聲明為子類(您可以在創建新類時執行此操作,然后輸入要作為子類的類名,如下圖所示)

在此處輸入圖片說明

並且您的popover視圖的標題將類似於:

@interface  CustomPopoverView : GameView

並將提供所有GameView的方法和屬性。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM