I'd go for a category on UIView
.
File --> New --> File --> Objective-C category. Name it something like EasyAdditionOfSubviews
, make it a category on UIView
.
UIView+EasyAdditionOfSubviews.h
#import <UIKit/UIKit.h>
@interface UIView (EasyAdditionOfSubviews)
- (void)addSubviews:(NSArray *)views;
@end
UIView+EasyAdditionOfSubviews.m
#import "UIView+EasyAdditionOfSubviews.h"
@implementation UIView (EasyAdditionOfSubviews)
- (void)addSubviews:(NSArray *)views
{
for (UIView *view in views) {
if ([view isKindOfClass:[UIView class]]) {
[self addSubview:view];
}
}
}
@end
This way, you just #import UIView+EasyAdditionOfSubviews.h
anywhere you want to be able to add an array of views at a time.
And you're better off making sure that what you're passing to addSubview:
is indeed a UIView
, otherwise you risk a crash (for example, try passing it an NSArray
).
But to address your wider concern:
But if there were several dozen or perhaps hundreds of UI components, adding each of them one at time would add dozens to hundreds of lines of code to my project.
If you're building a UI programmatically, you want to be exactly sure what, how, and when subviews are added to a view; it's perfectly fine to be explicit when adding a subview to a view.
As a matter of fact, your workaround to not explicitly adding the subview to its superview is... to explicitly add it to an array, which you then add to the superview. Not good for brevity!