iOS 對UIAlertController內的輸入框進行輸入監聽,實時改變確定、取消按鈕顏色


1、創建UIAlertController

UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"新建" message:@"" preferredStyle:UIAlertControllerStyleAlert];

2、添加一個輸入框 添加輸入框文字改變監聽

[alertController addTextFieldWithConfigurationHandler:^(UITextField *textField){

        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(alertTextFieldDidChange:) name:UITextFieldTextDidChangeNotification object:textField];

        textField.placeholder = @"請輸入全稱";

    }];

3、在確定和取消按鈕事件中相應的移除監聽

UIAlertAction *cancleAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {

        [[NSNotificationCenter defaultCenter] removeObserver:self name:UITextFieldTextDidChangeNotification object:nil];

    }];

    UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"確認" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {

        UITextField * wordNameTextField = alertController.textFields.firstObject;//獲取到textField

        [[NSNotificationCenter defaultCenter] removeObserver:self name:UITextFieldTextDidChangeNotification object:nil];

    }];

    okAction.enabled = NO;//此處確定按鈕在輸入框內沒有內容時置灰不可用

    [alertController addAction:cancleAction];

    [alertController addAction:okAction];

    [self presentViewController:alertController animated:YES completion:nil];

 

4、實現監聽方法

- (void)alertTextFieldDidChange:(NSNotification *)notification{

    UIAlertController *alertController = (UIAlertController *)self.presentedViewController;

    if (alertController) {

        UITextField *wordNameTextField = alertController.textFields.firstObject;

        UIAlertAction *okAction = alertController.actions.lastObject;

        okAction.enabled = ![@"" isEqualToString:wordNameTextField.text];//輸入框有內容時可用

    }

}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM