1.普通警告框
IOS的SDK中提供了一個方便的類庫UIAlertView,配合着不同參數來使用此類可以做出大多數的警告框,如下代碼是IOS最簡單的警告框。
1 UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"你好" message:@"我是普通警告框"
delegate:nil cancelButtonTitle:@"好的" otherButtonTitles: nil]; 2 [alert show];
當警告框創建完成后,我們可以在想顯示的地方調用show方法。但是,如果在調試過程中跑過這一步會發現,並不是“show”這行代碼一跑,我們的警告框就顯示出來,而是要繼續走完剩余的代碼,在當前消息循環結束后,次警告框才會自動彈出。
注:所謂的當前消息循環結束,可以理解為:流程全部跑完,比如函數一直跑,跑到函數尾部返回外面一層函數,再繼續跑返回更外面一層當此類推,直到跑到最外面那層的函數的尾部,下一步就出了最外面那層函數,隨后程序控制權交給當前消息循環。如果是主線程,則仍然不停循環等候新消息,如果是子線程,則此子線程結束。
對於UIAlertView的界面來說,一般無論點擊任何按鈕,此警告框就會消失。
如果想知道是按下哪一個按鈕的話,需要添加警告框的代理回調方法:
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex { id alertbutton = [alertView buttonTitleAtIndex:buttonIndex]; NSLog(@"按下了[%@]按鈕",alertbutton); }
通過此代理方法,開發者能明確直到那個警告框的那個按鈕被點擊了。
最多可以有5個按鈕,更多的話界面會有異常情況發生。運行結果如下:
2.無按鈕警告框
利用警告框的模態特性,來模擬一些屏蔽用戶操作的現象。
我們下面做一個警告框,在上面去掉所有元素,增加一個轉動的進度圈來表明任務正在執行,這樣就能達到我們的目的了,代碼如下。
-(void)showNoButtonAlert { UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"請稍等" message:nil delegate:self cancelButtonTitle:nil otherButtonTitles:nil]; [alert show]; alert.backgroundColor = [UIColor blackColor]; //無敵風火輪 UIActivityIndicatorView *actIndicator = [[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray]; //CGRect alertbounds=alert.bounds; //位置設置好 actIndicator.frame=CGRectMake(0, 0, 30, 30); actIndicator.center = CGPointMake(CGRectGetWidth(alert.bounds)/2, CGRectGetHeight(alert.bounds)-40.0f); //動起來 [actIndicator startAnimating]; [alert addSubview:actIndicator]; //過三秒消失 [self performSelector:@selector(dismissAlert:) withObject:alert afterDelay:3.0f]; } -(void)dismissAlert:(UIAlertView *)aAlertView { if(aAlertView) { //警告框消失 [aAlertView dismissWithClickedButtonIndex:0 animated:YES]; } }
3.顯示文本輸入框的警告框(登陸框)
在警告框上顯示一個文本輸入框表明用戶的輸入區域,文本框下面則是提供兩個按鈕:確認和取消。具體代碼如下:
-(void)showTextInputAlert { UITextField *txtField=nil; UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"你好" message:@"請輸入新題目:\n\n\n\n" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"確定", nil]; alert.alertViewStyle = UIAlertViewStyleLoginAndPasswordInput; //顯示之前配置txtField txtField = [alert textFieldAtIndex:0]; if(txtField) { txtField.placeholder=@"請輸入用戶名"; txtField.clearButtonMode = UITextFieldViewModeWhileEditing; } txtField = [alert textFieldAtIndex:1]; if(txtField) { txtField.placeholder =@"請輸入密碼"; txtField.clearButtonMode = UITextFieldViewModeWhileEditing; } //alert.tag=kalertTextInputType; [alert show]; NSLog(@"%@",txtField.text); } -(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex { id clickButton=[alertView buttonTitleAtIndex:buttonIndex]; NSLog(@"按下了%@按鈕",clickButton); id tmp=nil; }
顯示效果如下:其根據alert.alertViewStyle不同,顯示的也不同