2011-08-11 80 views
2

是否有可能爲Xcode中的一個IBAction編程多個UIAlertView以隨機顯示。例如:我正在製作一個隨機顯示多個​​問題的應用程序,當按下提交按鈕時,會顯示一條提示,說明答案是否正確。我希望在那裏爲警報提供不同的消息,例如一次顯示一條消息,然後下一次隨機顯示不同的消息。我將如何編程?我可以在Xcode中爲一個IBAction使用多個UIAlertViews嗎?

回答

2

在你的.h:

@interface MyViewController : UIViewController { 
    NSArray *messages; 
} 

@property (nonatomic, retain) NSArray *messages; 

在您的m

@implementation MyViewController 
@synthesize messages; 

- (dealloc) { 
    [messages release]; 
} 

- (void)viewDidLoad { 
    messages = [[NSArray alloc] initWithObjects:@"Funny Message", @"Even Funnier Message", @"Hilarious message", @"ROFL", @"OK this is getting boring...", nil]; 
} 

當你需要一個警告:

NSUInteger messageCount = [messages count]; 
int randomMessageIndex = arc4random() % messageCount; 

UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Title" message:[messages objectAtIndex:randomMessageIndex] delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil]; 
[alert show]; 
[alert release]; 
+0

它說的消息是一個未聲明的標識符...什麼我需要做的,解決這個問題? –

+0

在您的.h中聲明消息 - 請參閱更新後的問題 –

+0

當我運行代碼時,該程序適用於一個問題,但它會崩潰並顯示錯誤「Program received signal:」EXC_BAD_ACCESS「」我在做什麼錯?我有複製並粘貼你的代碼,所以我知道它的輸入都是正確的。 –

1

定義項目的下面的宏:

爲msg部分a試試隨機指數一個陣列

#define KAlert(TITLE,MSG) [[[[UIAlertView alloc] initWithTitle:(TITLE) 
      message:(MSG) 
     delegate:nil 
cancelButtonTitle:@"OK" 
otherButtonTitles:nil] autorelease] show] 

這可以作爲簡單的調用:

KAlert(@"Title", @"Message"); 

or KAlert(@"Title",@"[youarray objectatindex:randindex]"); 
相關問題