我的应用程序上有一个视图控制器,用户可以在其中输入个人信息。有一个取消选项会弹出一个警报,通知他们如果不保存数据,他们将丢失数据。我只想在此视图控制器中的任何文本字段具有 [.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];
}