有几种不同的方法可以做到这一点。您可以使用if statement
,根据条件创建不同的UIAlertView
。
选项1:
- (IBAction)btnClicked:(id)sender
{
UIAlertView *ourAlertView; // Create the local variable, we don't need to create multiple ones we can just set to the one.
// This is your if statement to determine if your condition has been met
// Whatever that condition is here we're going to assume you have set a BOOL
// flag before hand called failed.
if(!failed) {
ourAlertView = [[UIAlertView alloc] initWithTitle:@"Recommendations"
message:@"We recommend..."
delegate:self // Very important
cancelButtonTitle:@"No"
otherButtonTitles:@"Yes", nil];
[ourAlertView setTag:0]; // Would recommend setting a tag to determine which one has been used in the delegate methods.
} else { // else if() if you want more then 2
ourAlertView = [[UIAlertView alloc] initWithTitle:@"Sorry"
message:@"We're sorry..."
delegate:self // Very important
cancelButtonTitle:@"OK"
otherButtonTitles:nil];
[ourAlertView setTag:1];
}
[ourAlertView show];
}
第二种办法很简单,但我们会做以下,仍使用if statement
但我们只建立一个UIAlertView
选项2:
- (IBAction)btnClicked:(id)sender
{
// We create an empty `UIAlertView` only setting the delegate to self.
UIAlertView *ourAlertView = [[UIAlertView alloc] initWithTitle:nil
message:nil
delegate:self // Very important
cancelButtonTitle:nil
otherButtonTitles:nil];
if(!failed) {
[ourAlertView setTitle:@"Recommendations"];
[ourAlertView setMessage:@"We recommend..."];
[ourAlertView addButtonWithTitle:@"No"];
[ourAlertView addButtonWithTitle:@"Yes"];
[ourAlertView setCancelButtonIndex:0];
[ourAlertView setTag:0];
} else {
[ourAlertView setTitle:@"Sorry"];
[ourAlertView setMessage:@"We're sorry..."];
[ourAlertView addButtonWithTitle:@"OK"];
[ourAlertView setCancelButtonIndex:0];
[ourAlertView setTag:1];
}
[ourAlertView show];
}
但是最重要的需要的东西(那就是,如果你想让它正常工作),很多人忘记的是UIAlertViewDelegate
。
所以在你.h
文件,你必须在@interface
设置你需要做的
@interface MySubClass : MySuperClass <UIAlertViewDelegate>
这将允许您使用以下方法从UIAlertViewDelegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex
- (void)alertView:(UIAlertView *)alertView willDismissWithButtonIndex:(NSInteger)buttonIndex
- (void)alertViewCancel:(UIAlertView *)alertView
- (BOOL)alertViewShouldEnableFirstOtherButton:(UIAlertView *)
- (void)didPresentAlertView:(UIAlertView *)alertView
- (void)willPresentAlertView:(UIAlertView *)alertView
结帐两个UIAlertView
Apple Documentation和UIAlertViewDelegate
Apple Documentation
非常重要否关于UIAlertView
的苹果文档中有关子类化的问题。
UIAlertView类旨在按原样使用,不支持子类。这个类的视图层次是私有的,不能修改
'if(condition){create alertView} else {create other alertView}'?! –
条件是什么?你听说过“if语句”吗? – Popeye