cory ginsberg
cory ginsberg

Reputation: 2897

Can I have multiple UIAlertViews for one IBAction in Xcode?

Is it possible to program multiple UIAlertViews for one IBAction in Xcode to show at random. For example: I am making an app with multiple questions shown at random, when the submit button is pressed, an alert is shown saying if the answer is correct or not. I want there to be different messages for the alert such as one time it shows one message, then the next time it shows a different message at random. How would I program this?

Upvotes: 2

Views: 601

Answers (2)

Karthikeyan
Karthikeyan

Reputation: 1790

define the following macro for the project:

for the msg section as try a Array with random Index

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

Which could be used as simple call:

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

or KAlert(@"Title",@"[youarray objectatindex:randindex]");

Upvotes: 1

Alex Coplan
Alex Coplan

Reputation: 13361

In your .h:

@interface MyViewController : UIViewController { 
    NSArray *messages;
}

@property (nonatomic, retain) NSArray *messages;

In your .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];
}

When you need an alert:

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];

Upvotes: 2

Related Questions