iosuiviewuitextfieldfast-enumeration

How to enumerate through UITextFields on iOS


Which is the correct way of enumerating through sub views to find text fields?

NSMutableArray *mutableTFs = [[NSMutableArray alloc] init];

for (UIView *view in [self.view subviews]) {
    if ([view isKindOfClass:[UITextField class]]) {            
        [mutableTFs addObject:view];
    }
}

OR

NSMutableArray *mutableTFs = [[NSMutableArray alloc] init];

for (UITextField *textField in [self.view subviews]) {
    [mutableTFs addObject:textField];
}

I know this isn't the correct wording, but what I don't understand is if it is the top method, how do you 'convert' it from a view to a text field?


Solution

  • Which is the correct way of enumerating through sub views to find text fields?

    The first method is the correct one. The second method will iterate over all the subviews, not just the subviews with type UITextField. The type in the for() is only a hint to the compiler.

    For more information, see this question.

    how do you 'convert' it from a view to a text field?

    This is what typecasting is for.

    for (UIView *view in [self.view subviews]) {
        if ([view isKindOfClass:[UITextField class]]) {
            // you don't need to cast just to add to the array         
            [mutableTFs addObject:view];
            // typecasting works as it does in C
            UITextField *textField = (UITextField *)view;
            // do something with textField
        }
    }