iOS中UIAlertView(警告框)常用方法總結


 摘要:在iOS8之后,UIAlertView和UIActionSheet這兩個控件被UIAlertController代替,但是這兩個控件依然可以使用。這篇博客主要總結UIAlertView的常用方法。iOS9 UIAlertView不能用了

 

一、初始化方法

- (instancetype)initWithTitle:(NSString *)title message:(NSString*)message delegate:(id /*<UIAlertViewDelegate>*/)delegate cancelButtonTitle:(NSString *)cancelButtonTitle otherButtonTitles:(NSString *)otherButtonTitles, ...;

這個方法通過設置一個標題,內容,代理和一些按鈕的標題創建警告框,代碼示例如下:

?
1
2
    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;

風格的枚舉如下

 
1
2
3
4
5
6
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;

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM