Get an array of all UITextFields

How can I get an array of all UITextFields in the view controller?

EDIT: I don't want to hardcode the text fields into an array. I really want to get the list inside the delegate from all fields from the calling object of that delegate.

+6
source share
5 answers

Recursive implementation for finding all subviews subzones: (this way you catch text fields embedded in uiscrollview, etc.)

-(NSArray*)findAllTextFieldsInView:(UIView*)view{ NSMutableArray* textfieldarray = [[[NSMutableArray alloc] init] autorelease]; for(id x in [view subviews]){ if([x isKindOfClass:[UITextField class]]) [textfieldarray addObject:x]; if([x respondsToSelector:@selector(subviews)]){ // if it has subviews, loop through those, too [textfieldarray addObjectsFromArray:[self findAllTextFieldsInView:x]]; } } return textfieldarray; } -(void)myMethod{ NSArray* allTextFields = [self findAllTextFieldsInView:[self view]]; // ... } 
+16
source

If you know that you need an NSArray containing all of the UITextField , then why not add them to the array?

 NSMutableArray *textFields = [[NSMutableArray alloc] init]; UITextField *textField = [[UITextField alloc] initWithFrame:myFrame]; [textFields addObject:textField]; // <- repeat for each UITextField 

If you are using a thread, use IBOutletCollection

 @property (nonatomic, retain) IBOutletCollection(UITextField) NSArray *textFields; 

Then connect all UITextField to this array

+3
source

-Use the following code to get an array that contains the text values โ€‹โ€‹of all the UITextField presented in the view:

  NSMutableArray *addressArray=[[NSMutableArray alloc] init]; for(id aSubView in [self.view subviews]) { if([aSubView isKindOfClass:[UITextField class]]) { UITextField *textField=(UITextField*)aSubView; [addressArray addObject:textField.text]; } } NSLog(@"%@", addressArray); 
+1
source

You can view views of controller routines.

Here's a rough example:

 NSMutableArray *arrOfTextFields = [NSMutableArray array]; for (id subView in self.view.subviews) { if ([subView isKindOfClass:[UITextField class]]) [arrOfTextFields addObject:subView]; } 
-1
source

EDIT Recursion without a global variable (Tim only)

 -(NSArray*)performUIElementSearchForClass:(Class)targetClass onView:(UIView*)root{ NSMutableArray *searchCollection = [[[NSMutableArray alloc] init] autorelease]; for(UIView *subview in root.subviews){ if ([subView isKindOfClass:targetClass]) [searchCollection addObject:subview]; if(subview.subviews.count > 0) [searchCollection addObjectsFromArray:[self performUIElementSearchForClass:targetClass onView:subview]]; } return searchCollection; } 
-1
source

Source: https://habr.com/ru/post/905946/


All Articles