iOS8新特性---更優雅的彈窗

iOS8之后新增了UIAlertController用來取代UIAlertView以及UIActionSheet,它整合了以上兩個控件的功能,并且提供了更優雅的創建各種選項的方式.

廢話不多說,直接上工程.
新建一個工程,在sb里面添加一個Segment用于分別顯示UIAlertView以及UIActionSheet,添加一個start按鈕用于出發彈窗.

8A3F4193-1684-41A4-9F44-9CB8EEF4D1D1.png.jpg

點擊start觸發彈窗,選擇alert或者action分別提供兩種彈窗模式.
不多廢話,直接上代碼,注意點都在注釋里面寫清楚了.

- (IBAction)start:(UIButton *)sender {
    
    UIAlertControllerStyle style;
    switch (self.seguement.selectedSegmentIndex) {
        case 0:
            style = UIAlertControllerStyleAlert;
            break;
            
        case 1:
            style = UIAlertControllerStyleActionSheet;
            break;
        default:
            break;
    }
    
    //初始化alertController
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"TITLE" message:@"MESSAGE" preferredStyle:style];
    
    
    //初始化3個alertAction,block里面直接是點擊了該選項的回調
    //UIAlertActionStyleDefault默認樣式
    UIAlertAction *defaultItem = [UIAlertAction actionWithTitle:@"defaultItem" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
        NSLog(@"點擊了defaultItem");
    }];
    //UIAlertActionStyleCancel取消按鈕,無論添加順序如何,cancle強制顯示在最下面
    UIAlertAction *cancaleItem = [UIAlertAction actionWithTitle:@"cancaleItem" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
        NSLog(@"點擊了cancaleItem");
    }];
    //UIAlertActionStyleDestructive警示樣式,紅色字體
    UIAlertAction *destructiveItem = [UIAlertAction actionWithTitle:@"destructiveItem" style:UIAlertActionStyleDestructive handler:^(UIAlertAction *action) {
        NSLog(@"點擊了destructiveItem");
    }];
    
    //給alertcontroller添加action事件,會按照添加順序創建選項
    [alertController addAction:defaultItem];
    [alertController addAction:cancaleItem];
    [alertController addAction:destructiveItem];
    
    //如果是UIAlertControllerStyleAlert樣式,還可以添加輸入框
    if (style == UIAlertControllerStyleAlert) {
        [alertController addTextFieldWithConfigurationHandler:^(UITextField *textField) {
            textField.font = [UIFont fontWithName:@"AvenirNext-Medium" size:textField.font.pointSize];
            textField.placeholder = @"enjoy coding";
        }];
    }
    
    //彈出alert只需要modal出alertController即可
    [self presentViewController:alertController animated:YES completion:nil];
}

最終展示:


1.jpg

2.jpg

我們可以看到,使用UIAlertController不需要在以前的alertview的代理方法里面判斷各種index執行各種事件了,無益大大的簡化了代碼,如果iOS以后請果斷放棄alertview跟actionsheet吧,當然alertview跟actionsheet還是可以繼續使用的. (求一個不用支持iOS7的公司Orz)
github地址戳這里
have fun~

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容