UIAlertController(警告欄) 自學之初體驗

UIAlertController有兩種樣式  preferredStyle:數組

UIAlertControllerStyleAlert (位於屏幕的中部)spa

UIAlertControllerStyleActionSheet(位於屏幕的下方)
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"標題" message:@"默罕默德~本拉登" preferredStyle:UIAlertControllerStyleAlert];  //UIAlertController的建立server

UIAlertAction是UIAlertController的按鈕樣式
title按鈕的名稱,style按鈕的樣式,handler處理層序(點擊按鈕執行的代碼)
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消cancel" style:UIAlertActionStyleCancel handler:nil];
    UIAlertAction *defaultAction = [UIAlertAction actionWithTitle:@"默認" style:UIAlertActionStyleDefault handler:nil];
    UIAlertAction *resetAction = [UIAlertAction actionWithTitle:@"重置" style:UIAlertActionStyleDestructive handler:nil];
    //添加按鈕到UIAlertController上
    [alert addAction:cancelAction];
    [alert addAction:defaultAction];
    [alert addAction:resetAction];對象

 一、文本輸入框只能添加到Alert的風格中,ActionSheet是不容許的;blog

 二、UIAlertController具備只讀屬性的textFields數組,須要可直接按本身須要的順序添加;事件

 三、添加方式是使用block,參數是UITextField;get

 四、添加UITextField監聽方法和實現方法。it

    //添加文本輸入框
    [alert addTextFieldWithConfigurationHandler:^(UITextField *textField){
        textField.placeholder = @"登錄";
        //能夠爲textField添加事件
    }];
    [alert addTextFieldWithConfigurationHandler:^(UITextField *textField){
        textField.placeholder = @"密碼";
        textField.secureTextEntry = YES;
        //能夠爲textField添加事件
    }];io

添加一個事件能夠用來輸出用戶名和密碼(textFields是屬性,是一個數組)ast

UIAlertAction *getAction = [UIAlertAction actionWithTitle:@"肯定" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action){
            UITextField *login = alert.textFields[0];
            UITextField *passWord = alert.textFields[1];
            NSLog(@"登錄:%@   密碼:%@",login.text,passWord.text);
        }];//獲取textField的文本內容
        [alert addAction:getAction];


若是要監聽textField開始,結束,改變狀態,須要添加監聽代碼
    [alert addTextFieldWithConfigurationHandler:^(UITextField *textField){
            textField.placeholder = @"添加監聽代碼";
            [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(alertTextFieldDidChange:) name:UITextFieldTextDidChangeNotification object:textField];
        }];
    [self presentViewController:alert animated:YES completion:^{
    }];  //模態推送到頁面上

//監聽的方法
-(void)alertTextFieldDidChange:(NSNotification *)notification{
    UIAlertController *alertController = (UIAlertController *)self.presentedViewController;
    if (alertController) {
        //爲textFields數組中下標爲2的textField爲監聽對象
        //也是alertController.textFields.lastObject
        UITextField *listen = alertController.textFields[2];
        //限制,若是listen限制輸入長度在5個字符內,不然不容許點擊默認Defult鍵
        //當UITextField輸入字數超過5個,按鈕變灰色,enable爲NO
        UIAlertAction *action = alertController.actions.lastObject;
        action.enabled = listen.text.length<=5;
    }

相關文章
相關標籤/搜索