我想编写一个通用方法来验证所有 UIControls,如 NSTextField、NSTextView 等。如果任何必填字段为空,则应显示一个合并的警报,其中第一个控件作为焦点/第一响应者。
我已经实现了这样的东西:
-(NSInteger)lengthAfterTrimmingSpaces:(NSString *)string{
return [[string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] length];
}
-(NSDictionary *)createWarningMessageForMandatoryFields:(NSArray *)uiObjects{
NSMutableString *warningString=[NSMutableString stringWithString:@"Enter "];
id firstInvalidatedControl=nil;
for (NSDictionary *object in uiObjects) {
NSString *key=[object allKeys][0];
id control=object[key];
if ([control isKindOfClass:[NSTextField class]]) {
if ([self lengthAfterTrimmingSpaces:[control stringValue]]==0){
[warningString appendString:key];
[warningString appendString:@", "];
if (firstInvalidatedControl==nil) {
firstInvalidatedControl=control;
}
}
}
else if ([control isKindOfClass:[NSTextView class]]) {
if ([self lengthAfterTrimmingSpaces:[control string]]==0){
[warningString appendString:key];
[warningString appendString:@", "];
if (firstInvalidatedControl==nil) {
firstInvalidatedControl=control;
}
}
}
}
if (firstInvalidatedControl==nil) {
return @{@"warningString":@"Success"};
}
else{
warningString =[[warningString substringToIndex:[warningString length] - 2]mutableCopy];
return @{@"warningString":warningString, @"control":firstInvalidatedControl};
}
}
-(BOOL)validateMandatoryFields{
NSMutableArray *uiObjects=[NSMutableArray array];
[uiObjects addObject:@{@"Segment Name":self.segmentName}];
[uiObjects addObject:@{@"Code":self.code}];
[uiObjects addObject:@{@"Desciption":self.description}];
NSDictionary *warningAndControl=[self createWarningMessageForMandatoryFields:uiObjects];
if ([warningAndControl[@"warningString"] isEqualToString:@"Success"]) {
return YES;
}
else{
[[self window] makeFirstResponder:warningAndControl[@"control"]];
NSRunAlertPanel(@"Warning", warningAndControl[@"warningString"], @"OK", nil, nil);
return NO;
}
}
- (IBAction)save:(id)sender {
NSLog(@"%d",[self validateMandatoryFields]);
}
现在我想让它更加通用,因为对于每种我都在进行类内省,然后检索值(stringValue/string 等)。
对此的任何其他建议也表示赞赏。