UIAlertController在IOS8中新加的,整合了UIAlertView和UIActionSheet兩個控件code
UIAlertView和UIActionSheet在IOS9中已經廢棄server
======================================================================事件
UIAlertControllerStyleAlert UIAlertControllerStyleActionSheet
//初始化UIAlertController UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:@"請輸入message" preferredStyle:UIAlertControllerStyleAlert]; //建立點擊按鈕 UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:nil]; UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) { //添加點擊事件 } //添加按鈕到UIAlertController [alert addAction:cancelAction]; [alert addAction:okAction]; [self presentViewController:alert animated:YES completion:nil];
此外,還能夠在AlertView(僅限在當前模式,ActionSheet中不可用)中添加TextField,以下it
//在畫面中添加TextField [alert addTextFieldWithConfigurationHandler:^(UITextField *textField) { //添加提示信息 textField.placeholder = @"登錄,添加了監聽,輸入少於5個字符"; // 消息通知機制(KVO): 監聽--註冊通知 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textFileChange:) name:UITextFieldTextDidChangeNotification object:textField]; }]; /** AlertView中TextField監聽*/ -(void)textFileChange:(NSNotification *)notification{ UITextField *textField = (UITextField *)notification.object; UIAlertController *alert = (UIAlertController *)self.presentedViewController; UITextField *listen = alert.textFields[1]; UIAlertAction *action = alert.actions.lastObject; //若是textFiled的長度超過5個字符,最後一個default按鈕點擊不可 action.enabled = (listen.text.length <= 5); }
//初始化 UIAlertController *actionSheet = [UIAlertController alertControllerWithTitle:@"UIAlertControllerStyleActionSheet" message:@"Switched" preferredStyle:UIAlertControllerStyleActionSheet]; //建立按鈕 UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:nil]; UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action){ //添加點擊事件 }]; //添加按鈕 [actionSheet addAction:cancelAction]; [actionSheet addAction:okAction]; [self presentViewController:actionSheet animated:YES completion:nil];