私のアプリには、ユーザーが個人情報を入力するビュー コントローラーがあります。保存しないとデータが失われることを通知するアラートを表示するキャンセル オプションがあります。このView Controllerのテキストフィールドに [.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];
}