簡體   English   中英

檢查UITextFields是否有文字

[英]Check UITextFields for text

我的應用程序上有一個視圖控制器,用戶可以在其中輸入個人信息。 有一個取消選項,它會彈出一個警報,通知他們如果不保存數據,它們將丟失數據。 我只想在此視圖控制器中的任何文本字段具有[.text.length> 0]的情況下顯示此警報(我有大約20個文本字段,如果有甚至1個字符,它都應拉出警報)。 我可以在if語句中手動命名每個文本字段,但希望有某種方法可以檢查視圖控制器中的所有文本字段?

這是我到目前為止的內容:

for (UIView *view in [self.view subviews]) {
    if ([view isKindOfClass:[UITextField class]]) {
        UITextField *textField = (UITextField *)view;
        if(textField.text.length >= 1){
            UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Cancel?"
                                                                message:@"If you leave before saving, the athlete will be lost. Are you sure you want to cancel?"
                                                               delegate:self
                                                      cancelButtonTitle:@"No"
                                                      otherButtonTitles:@"Yes", nil];

            [alertView show];
        }
        if(textField.text.length == 0){
            [[self navigationController] popViewControllerAnimated:YES];
        }
    }
}

我想檢查是否有帶值的文本字段,但這會導致錯誤,因為它在完成for循環之前檢查textField.text.length == 0。

解:

BOOL areAnyTextFieldsFilled = NO;
for (UIView *view in [self.view subviews]) {
    if ([view isKindOfClass:[UITextField class]]) {
        UITextField *textField = (UITextField *)view;
        if(textField.text.length >= 1){
            areAnyTextFieldsFilled = YES;

        }

    }
}
if(areAnyTextFieldsFilled == YES){
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Cancel?"
                                                        message:@"If you leave before saving, the athlete will be lost. Are you sure you want to cancel?"
                                                       delegate:self
                                              cancelButtonTitle:@"No"
                                              otherButtonTitles:@"Yes", nil];

    [alertView show];
}
else{
    [[self navigationController] popViewControllerAnimated:YES];
}

您可以使用標簽實現一些非常好的功能。 將每個標簽設置為一個特定的標簽1、2,...,20。然后,使用以下內容進行迭代:

    for (int x = 1; x < 21; x++)
    {
        UITextField *aTextField = (UITextField *) [self.view viewWithTag:x];
        //check here if text
    }

另外,為了提高效率,您可以設置一個從零開始的標志,並且如果用戶編輯textField,它將變為1。 然后它只會循環如果它是一個。


但是,對於您當前的方法,您可以做的是擁有一個標志(是的,再次,我愛他們:)),然后將其設置為零(可能在viewDidLoad中)。 如果遇到帶有單詞的文本字段,請將其設置為1。刪除當前的if(textField.text.length == 0)語句。 然后,之后只需檢查循環后標志是否仍== 0。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM