標籤:
IOS中UIAlertView(警告框)常用方法總結
一、初始化方法 - (instancetype)initWithTitle:(NSString *)title message:(NSString *)message delegate:(id /*<UIAlertViewDelegate>*/)delegate cancelButtonTitle:(NSString *)cancelButtonTitle otherButtonTitles:(NSString *)otherButtonTitles, ...;
這個方法通過設定一個標題,內容,代理和一些按鈕的標題建立警告框,程式碼範例如下:
UIAlertView * alert = [[UIAlertView alloc]initWithTitle:@"我的警告框" message:@"這是一個警告框" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"確定", nil]; [alert show];
效果如下:
注意:如果按鈕數超過兩個,將會建立成如下樣子:
如果按鈕數量超出螢幕顯示範圍,則會建立類似tableView的效果。
二、屬性與方法解析
標題屬性
@property(nonatomic,copy) NSString *title;
內容屬性
@property(nonatomic,copy) NSString *message;
添加一個按鈕,返回的是此按鈕的索引值
- (NSInteger)addButtonWithTitle:(NSString *)title;
返回根據按鈕索引按鈕標題
- (NSString *)buttonTitleAtIndex:(NSInteger)buttonIndex;
擷取按鈕數量
@property(nonatomic,readonly) NSInteger numberOfButtons;
設定將某一個按鈕設定為取消按鈕
@property(nonatomic) NSInteger cancelButtonIndex;
返回其他類型按鈕第一個的索引值
@property(nonatomic,readonly) NSInteger firstOtherButtonIndex;
警告框是否可見
@property(nonatomic,readonly,getter=isVisible) BOOL visible;
顯現警告框
- (void)show;
代碼類比點擊按鈕消失觸發方法
- (void)dismissWithClickedButtonIndex:(NSInteger)buttonIndex animated:(BOOL)animated;
設定警告框風格
@property(nonatomic,assign) UIAlertViewStyle alertViewStyle;
風格的枚舉如下
typedef NS_ENUM(NSInteger, UIAlertViewStyle) { UIAlertViewStyleDefault = 0,//預設風格 UIAlertViewStyleSecureTextInput,//密碼輸入框風格 UIAlertViewStylePlainTextInput,//普通輸入框風格 UIAlertViewStyleLoginAndPasswordInput//帳號密碼框風格};
這個方法設定文本輸入框的索引
- (UITextField *)textFieldAtIndex:(NSInteger)textFieldIndex;
三、UIAlertViewDelegate中的方法
點擊按鈕時觸發的方法
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex;
將要展現警告框時觸發的方法
- (void)willPresentAlertView:(UIAlertView *)alertView;
已經展現警告框時觸發的方法
- (void)didPresentAlertView:(UIAlertView *)alertView;
警告框將要消失時觸發的方法
- (void)alertView:(UIAlertView *)alertView willDismissWithButtonIndex:(NSInteger)buttonIndex;
警告框已經消失時觸發的方法
- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex;
設定是否允許第一個按鈕不是取消按鈕
- (BOOL)alertViewShouldEnableFirstOtherButton:(UIAlertView *)alertView;
IOS UIAlertView(警告框)方法總結