UIAlertController

UIAlertController

在iOS 8中,UIAlertController替代UIAlertView實(shí)現(xiàn)提醒功能

基礎(chǔ)使用

創(chuàng)建一個(gè)UIAlertController

UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"標(biāo)題" message:@"這個(gè)是UIAlertController的默認(rèn)樣式" preferredStyle:UIAlertControllerStyleAlert];

相比UIAlertView 不需要指定代理,無(wú)需初始化過(guò)程中指定按鈕.要注意樣式是對(duì)話框樣式還是上拉菜單樣式.

通過(guò)創(chuàng)建UIAlertAction的實(shí)例,您可以將動(dòng)作按鈕添加到控制器上。UIAlertAction由標(biāo)題字符串、樣式以及當(dāng)用戶選中該動(dòng)作時(shí)運(yùn)行的代碼塊組成。通過(guò)UIAlertActionStyle,您可以選擇如下三種動(dòng)作樣式:常規(guī)(default)、取消(cancel)以及警示(destruective)。為了實(shí)現(xiàn)原來(lái)我們?cè)趧?chuàng)建UIAlertView時(shí)創(chuàng)建的按鈕效果,我們只需創(chuàng)建這兩個(gè)動(dòng)作按鈕并將它們添加到控制器上即可.

UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"好的" style:UIAlertActionStyleDefault handler:nil];

[alertController addAction:cancelAction];
[alertController addAction:okAction];

最后,我們只需顯示這個(gè)對(duì)話框視圖控制器即可:

[self presentViewController:alertController animated:YES completion:nil];
74454-62d34cf2ee01cf66.png

按鈕顯示的次序取決于它們添加到對(duì)話框控制器上的次序

"警示"樣式

UIAlertAction *resetAction = [UIAlertAction actionWithTitle:@"重置" style:UIAlertActionStyleDestructive handler:nil];

[alertController addAction:resetAction];
74454-349d278fb8f9aaf6.png

可以看出,我們新增的那個(gè)“重置”按鈕變成了紅色。根據(jù)蘋(píng)果官方的定義,“警示”樣式的按鈕是用在可能會(huì)改變或刪除數(shù)據(jù)的操作上。因此用了紅色的醒目標(biāo)識(shí)來(lái)警示用戶。

文本對(duì)話框

UIAlertController極大的靈活性意味著您不必拘泥于內(nèi)置樣式。以前我們只能在默認(rèn)視圖、文本框視圖、密碼框視圖、登錄和密碼輸入框視圖中選擇,現(xiàn)在我們可以向?qū)υ捒蛑刑砑尤我鈹?shù)目的UITextField對(duì)象,并且可以使用所有的UITextField特性。當(dāng)您向?qū)υ捒蚩刂破髦刑砑游谋究驎r(shí),您需要指定一個(gè)用來(lái)配置文本框的代碼塊。

舉個(gè)栗子吧,要重新建立原來(lái)的登錄和密碼樣式對(duì)話框,我們可以向其中添加兩個(gè)文本框,然后用合適的占位符來(lái)配置它們,最后將密碼輸入框設(shè)置使用安全文本輸入。

UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"文本對(duì)話框" message:@"登錄和密碼對(duì)話框示例" preferredStyle:UIAlertControllerStyleAlert];

[alertController addTextFieldWithConfigurationHandler:^(UITextField *textField){
    textField.placeholder = @"登錄";
}];

[alertController addTextFieldWithConfigurationHandler:^(UITextField *textField) {
    textField.placeholder = @"密碼";
    textField.secureTextEntry = YES;
}];

在“好的”按鈕按下時(shí),我們讓程序讀取文本框中的值。

UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"好的" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
    UITextField *login = alertController.textFields.firstObject;
    UITextField *password = alertController.textFields.lastObject;
    ...
}];
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容