我想验证UITextField并在出现错误时显示UIAlertView。
以前我使用过以下代码。它与2个UITexfields完美配合,但有许多UITextfield,这是不可能的。
有关如何显示UIAlertView以验证我的UITexfields的任何提示吗?
- (void)processFieldEntries {
NSString *usernameString = usernameField.text;
NSString *passwordString = passwordField.text;
NSString *firstNameString = firstNameField.text;
NSString *nameString = nameField.text;
NSString *cityString = cityField.text;
NSString *errorText = @"Enter";
NSString *usernameBlankText = @" a username";
NSString *passwordBlankText = @" a password";
NSString *prenomBlankText = @" a firstname";
NSString *nomBlankText = @" a name";
NSString *joinText = @", ";
BOOL textError = NO;
if (identifiantString.length == 0 || motDePasseString.length == 0 || prenomString.length == 0 || nomString.length == 0 || idPoubelle.length == 0) {
textError = YES;
if (usernameString.length == 0) {
errorText = [errorText stringByAppendingString:usernameBlankText];
}
if (usernameString.length == 0 || passwordString.length == 0) {
if (usernameString.length == 0) {
errorText = [errorText stringByAppendingString:joinText];
}
errorText = [errorText stringByAppendingString:passwordBlankText];
}
}
if (textError) {
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:errorText message:nil delegate:self cancelButtonTitle:nil otherButtonTitles:@"Ok", nil];
[alertView show];
return;
}
}
答案 0 :(得分:0)
我会做这样的事情:
- (void)processFieldEntries {
NSString *usernameString = usernameField.text;
NSString *passwordString = passwordField.text;
NSString *firstNameString = firstNameField.text;
NSString *nameString = nameField.text;
NSString *cityString = cityField.text;
NSMutableArray *errors = [NSMutableArray array];
if (usernameString.length == 0) {
[errors addObject:@"a username"];
}
if (passwordString.length == 0) {
[errors addObject:@"a password"];
}
if (firstNameString.length == 0) {
[errors addObject:@"a first name"];
}
if (nameString.length == 0) {
[errors addObject:@"a name"];
}
if (errors.count) {
NSString *message = [NSString stringWithFormat:@"Enter %@", [errors componentsJoinedByString:@", "]];
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Errors" message:message delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
[alertView show];
}
}
当然,这并不能很好地扩展。考虑创建一个文本字段和错误消息数组。然后,您可以迭代数组,而不是编写一长列if
语句。
答案 1 :(得分:0)
您还可以在用户输入信息时进行一些额外检查,因为例如名称不应包含除字母以外的数字或其他符号。
您可以做的一个很好的方法是从View Controller类实现UITextFieldDelegate协议。
然后为每个UITextField对象设置tag属性。
协议有这个有用的方法:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string;
每次在任何文本框中定位时都会调用它。
然后你可以检查:
switch (textfield.tag)
{
case TEXT_FIELD_FOR_FIRST_NAME_TAG:
{
if (!validateFirstNameFunction) { /* Display some error */ }
break;
}
case TEXT_FIELD_FOR_LAST_NAME_TAG:
{
if (!validateLastNameFunction) { /* Display some error */ }
break;
}
// And so on...
}
尝试分离功能,这将使代码更清晰,更易读。
希望它也为你带来一些价值:)