Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get array of all UITextFields

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

EDIT: I do not want to hardcode the textfields into an array. I actually want to get the list inside the delegate of all the fields from the caller of that delegate.

like image 219
Bot Avatar asked Jan 13 '12 21:01

Bot


4 Answers

Recursive implementation to search all subviews' subviews: (this way you catch textfields 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]];
   // ...
 }
like image 154
Tim Avatar answered Oct 19 '22 16:10

Tim


If you know you need an NSArray containing all the UITextField's then why not add them to an array?

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

UITextField *textField = [[UITextField alloc] initWithFrame:myFrame];

[textFields addObject:textField]; // <- repeat for each UITextField

If you are using a nib then use an IBOutletCollection

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

Then connect all the UITextField's to that array

like image 27
Paul.s Avatar answered Oct 19 '22 15:10

Paul.s


-Use following code to get array that contains text values of all UITextField presented on 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);
like image 32
Himanshu Mahajan Avatar answered Oct 19 '22 14:10

Himanshu Mahajan


extension UIView 
{
   class func getAllSubviewsOfType<T: UIView>(view: UIView) -> [T] 
   {
       return view.subviews.flatMap { subView -> [T] in
       var result = UIView.getAllSubviewsOfType(view: subView) as [T]
       if let view = subView as? T {
           result.append(view)
       }
       return result
     }
   }

   func getAllSubviewsWithType<T: UIView>() -> [T] {
       return UIView.getAllSubviewsOfType(view: self.view) as [T]
   }
}

How to use with Text Fields:

let textFields = self.view.getAllSubviewsWithType() as [UITextField]
like image 37
Nirav Bhatt Avatar answered Oct 19 '22 16:10

Nirav Bhatt