IPhone - what is the best way to display an error message below UITextfield

I have a form with many UIText fields, such as Name, password, email, etc., and during validation I want to display an error message for the fields below the corresponding text field.

What is the best way to do this. Any examples really help.

+3
source share
1 answer

Create a new object model containing a text box, label, and validation block. When the text field resigns the first responder, call the block to check if it is valid, and if not, display the label

Something like that

@protocol ValidationTextFieldDelegate

-(void) validationTextField:(ValidationTextField*)textField didResignWithResult:(BOOL)result;

@end

@interface ValidationTextField : NSObject <UITextFieldDelegate>

@property (nonatomic, strong) UITextField *textField;
@property (nonatomic, strong) UILabel *errorLabel;
@property (copy) void(^validationBlock)(BOOL);
@property (nonatomic, assign) id<ValidationTextFieldDelegate> delegate;

@end

@implementation ValidationTextField

-(void)textFieldDidEndEditing:(UITextField*)textField {
    BOOL result = self.validationBlock();

    self.errorLabel.hidden = result;

    if (self.delegate) {
        [self.delegate validationTextField:self didResignWithResult:result];
    }
}

And in your controller

-(void) validationTextField:(ValidationTextField*)textField didResignWithResult:(BOOL)result {
    if (!result) {
        int yOffset = textField.errorLabel.bounds.size.height;

        // Update here the frames of your other textfields, adding the yOffset to their frames
    }
}
+1
source

All Articles