iOS UIAlertController簡單使用方法

來源:互聯網
上載者:User

首先說下UIAlertView和UIActionSheet在iOS9之後蘋果官方就不推薦使用了,而是使用UIAlertController來替代。
有圖為證


所以學習一下UIAlertController的用法也是有必要的。

1.擷取UIAlertController的類對象:

UIAlertController *alertController =[UIAlertController alertControllerWithTitle:@"Success" message:nil preferredStyle:UIAlertControllerStyleAlert];

2.擷取UIAlertAction的類對象:


UIAlertAction *doneAction = [UIAlertAction actionWithTitle:@"Done" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
 
    NSLog(@"123");
}];

3.用UIAlertController的類對象alertController的addAction方法添加UIAlertAction的類對象:

[alertController addAction:doneAction];

4.使用window的根視圖模態出alertController


[[UIApplication sharedApplication].keyWindow.rootViewController presentViewController:alertController animated:YES completion:nil];

如果想用UIActionSheet類似的介面,只需要將第一步中的UIAlertControllerStyleAlert替換成UIAlertControllerStyleActionSheet即可。

如果程式用了這個API,那麼在iOS7上會導致crash,所以需要版本相容


UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"title" message:@"message" preferredStyle:UIAlertControllerStyleAlert]; 
                                 
UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]; 
                                 
UIAlertAction *confirm = [UIAlertAction actionWithTitle:@"確定" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action){ 
    [mainViewDelegate doBackupWithTag:BACKUP_STATISTICS_TAG_CONFIRM]; 
}]; 
                                 
[alert addAction:cancel]; 
[alert addAction:confirm]; 
[self presentViewController:alert animated:YES completion:nil]; 

可以看到,最大的區別,是UIAlertController不再使用delegate的方式來觸發回調,而是直接傳一個block
delegate和block並沒有本質區別,只是觸發回調的不同方式而已,解決的都是“在未來的某個時間,調用我”的問題。delegate的複用性更好一點,建立一個delegate執行個體之後,可以把它設定為多個控制項的delegate,減少了重複。block的優勢是更加直觀,閱讀起來更容易,因為代碼都在一處,不需要跳來跳去地讀代碼
但是現在既然蘋果官方使用block的頻率越來越高,或許這也代表了一種趨勢

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.