iOS中警告視圖的簡單應用
創建一個警告,具體代碼只有如下:
- - (void) presentSheet
- {
- UIAlertView *baseAlert = [[UIAlertView alloc]
- initWithTitle:@"Alert" message:@""
- delegate:self cancelButtonTitle:nil
- otherButtonTitles:@"OK", nil];
- [baseAlert show];
- }
類學習
UIAlertView類
繼承UIView
Use the UIAlertView class to display an alert message to the user. An alert view functions similar to but differs in appearance from an action sheet (an instance of UIActionSheet).
使用UIAlertView類顯示警告信息給用戶看。警告視圖函數類似但不同于從動作表上的呈現(UIActionSheet實例)
屬性:
delegate
title
message
visible
//這里可以看出在init方法調用的參數部分可以由屬性來設置
cancelButtonIndex:-1表示未設置.
firstOtherButtonIndex:此屬性只讀
numberOfButtons:按鈕個數,只讀
方法:
– initWithTitle:message:delegate:cancelButtonTitle:otherButtonTitles:
– show
– addButtonWithTitle:通過所給標題添加按鈕
– buttonTitleAtIndex:返回指定索引下的按鈕標題
– dismissWithClickedButtonIndex:animated:清除接收器,動畫可選
針對UIAlertView視圖類如何響應按鈕觸發?
這里要用到
UIAlertViewDelegate Protocol
此協議接口定義UIAlertView對象委托需要執行的方法
Responding to Actions
– alertView:clickedButtonAtIndex:當用戶在警告視圖點擊按鈕時發送給委托處理并響應
Customizing Behavior
– willPresentAlertView:警告視圖呈現給用戶前發送給委托
– didPresentAlertView:警告視圖呈現給用戶后發送給委托
– alertView:willDismissWithButtonIndex:在警告視圖清除前發送給委托
– alertView:didDismissWithButtonIndex:在警告視圖從屏幕離開后發送給委托
Canceling
– alertViewCancel:在警告視圖中止前發送給委托
整體來說,警告視圖類的方法和觸發事件都非常簡單
在寫觸發事件時需要繼承<UIAlertViewDelegate>協議接口
/************************************************************/
后續一例子:自動計時無按鈕警告
這個例子咋看是一個新的東西,仔細閱讀下代碼,就是使用NSTimer和UIAlertView
注意兩個地方:
1、創建警告視圖的時候,不要添加Button
2、Timer關閉警告視圖的時候,設置Repeat參數=No
參看代碼:
- - (void) performDismiss: (NSTimer *)timer
- {
- [baseAlert dismissWithClickedButtonIndex:0 animated:NO];
- [baseAlert release];
- baseAlert = NULL;
- }
- - (void) presentSheet
- {
- baseAlert = [[UIAlertView alloc]
- initWithTitle:@"Alert" message:@"\nMessage to user with asynchronous information"
- delegate:self cancelButtonTitle:nil
- otherButtonTitles: nil];//注意cancelButtonTitle和otherButtonTitles都nil
- [NSTimer scheduledTimerWithTimeInterval:3.0f
- target:self
- selector: @selector(performDismiss:)
- userInfo:nil repeats:NO];//注意repeats:NO
- [baseAlert show];
- }