문제

I'm sick of writing basic UIAlertView's, ie:

UIAlertView *alert = [[UIAlertView alloc] initWith...]] //etc

Instead of doing this, is it possible to put all this in a "helper" function, where I can return the buttonIndex, or whatever an alert usually returns?

For a simple helper function I guess you could feed parameters for the title, message, I'm not sure whether you can pass delegates in a parameter though, or bundle info.

In pseudo-code, it could be like this:

someValueOrObject = Print_Alert(Title="", Message="", Delegate="", Bundle="") // etc

Any help on this would be great.

Thanks

도움이 되었습니까?

해결책

This is what I wrote, when I got sick of doing the same:

-(void)alert:(NSString *)title withBody:(NSString *)message firstButtonNamed:(NSString *)firstButtonName {
  [self alert: title withBody: message firstButtonNamed: firstButtonName withExtraButtons: nil informing: nil];
}

-(void)alert:(NSString *)title withBody:(NSString *)message firstButtonNamed:(NSString *)firstButtonName informing:(id)delegate {
  [self alert: title withBody: message firstButtonNamed: firstButtonName withExtraButtons: nil informing: delegate];
}

-(void)alert:(NSString *)title withBody:(NSString *)message firstButtonNamed:(NSString *)firstButtonName withExtraButtons:(NSArray *)otherButtonTitles informing:(id)delegate {
  UIAlertView *alert = [[UIAlertView alloc]
              initWithTitle: title
              message: message
              delegate: delegate
              cancelButtonTitle: firstButtonName
              otherButtonTitles: nil];
  if (otherButtonTitles != nil) {  
    for (int i = 0; i < [otherButtonTitles count]; i++) {
      [alert addButtonWithTitle: (NSString *)[otherButtonTitles objectAtIndex: i]];
    }
  }
  [alert show];
  [alert release];
}

You can't write a function that will display an alert and then return a value like a buttonIndex though, because that value-returning only occurs when the user presses a button and your delegate does something.

In other words, the process of asking a question with the UIAlertView is an asynchronous one.

다른 팁

In 4.0+ you can simplify the alert code using blocks, a bit like this:

CCAlertView *alert = [[CCAlertView alloc]
    initWithTitle:@"Test Alert"
    message:@"See if the thing works."];
[alert addButtonWithTitle:@"Foo" block:^{ NSLog(@"Foo"); }];
[alert addButtonWithTitle:@"Bar" block:^{ NSLog(@"Bar"); }];
[alert addButtonWithTitle:@"Cancel" block:NULL];
[alert show];

See Lambda Alert on GitHub.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top