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];
按鈕顯示的次序取決于它們添加到對(duì)話框控制器上的次序
"警示"樣式
UIAlertAction *resetAction = [UIAlertAction actionWithTitle:@"重置" style:UIAlertActionStyleDestructive handler:nil];
[alertController addAction:resetAction];
可以看出掀虎,我們新增的那個(gè)“重置”按鈕變成了紅色凌盯。根據(jù)蘋果官方的定義付枫,“警示”樣式的按鈕是用在可能會(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;
...
}];