IOS 模態彈窗與操做版使用 UIAlertController

IOS8 之後UIAlertView 改用 UIAlertController 實現模態窗和操做板。UIAlertController 的使用與UIAlerView 很是不一樣,它其實是把彈窗內容與顯示方式、按鈕列表、分離。實現起來很是簡單。以下
1.調用靜態方法建立彈窗控制器 alertControllerWithTitle

聲明彈窗控制器,title 表示彈窗的標題,message表示彈窗文字內容,重點是preferredStyle 表示彈窗的顯示方式,UIAlertControllerStyleActionSheet操做版方式顯示,UIAlertControllerStyleAlert 模態窗方式網絡

// 建立控制器
    UIAlertController* alertConrtoll = [UIAlertController alertControllerWithTitle:@"錯誤" message:@"網絡錯誤,獲取失敗" preferredStyle:UIAlertControllerStyleActionSheet];
2.爲彈窗控制器增長按鈕 UIAlertAction

UIAlertActions 是彈窗按鈕類,經過靜態方法actionWithTitle 建立,style表示按鈕風格,handler是按鈕被點擊的回調函數。咱們建立完按鈕組件經過 addAction加入彈窗控制器函數

// 建立彈窗按鈕組件
    UIAlertAction* okBtn = [UIAlertAction actionWithTitle:@"好的" style:UIAlertActionStyleDefault handler: nil];
    UIAlertAction* cancelBtn = [UIAlertAction actionWithTitle:@"從新獲取" style:UIAlertActionStyleCancel handler: nil];
    // 添加按鈕
    [alertConrtoll addAction:okBtn];
    [alertConrtoll addAction:cancelBtn];
顯示彈窗

顯示彈窗和插入視圖控制器方法一致。code

[self presentViewController:alertConrtoll animated:YES completion:nil];
UIAlertController 屬性
名稱 類型 說明 默認值
title NSString 標題
preferredStyle UIAlertControllerStyle 彈窗顯示方式,只讀
actions NSArray<UIAlertAction *> 彈窗按鈕列表,只讀
UIAlertAction 屬性
名稱 類型 說明 默認值
enabled BOOL 是否啓用
title NSString 標題
style UIAlertActionStyle 按鈕風格 UIAlertActionStyleDefault
UIAlertController API
  • + (instancetype)alertControllerWithTitle:(nullable NSString *)title message:(nullable NSString *)message preferredStyle:(UIAlertControllerStyle)preferredStyle 建立彈窗控制器而且設置標題,內容,顯示風格
  • - (void)addTextFieldWithConfigurationHandler:(void (^ __nullable)(UITextField *textField))configurationHandler 添加可輸入彈窗
UIAlertAction API
  • + (instancetype)actionWithTitle:(nullable NSString *)title style:(UIAlertActionStyle)style handler:(void (^ __nullable)(UIAlertAction *action))handler 建立彈窗按鈕而且設置標題和風格、處理事件
相關文章
相關標籤/搜索