有幾種不同的方法可以做到這一點。您可以使用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