Skip to content

Instantly share code, notes, and snippets.

@rsaunders100
Created May 15, 2012 17:39
Show Gist options
  • Save rsaunders100/2703587 to your computer and use it in GitHub Desktop.
Save rsaunders100/2703587 to your computer and use it in GitHub Desktop.
(iOS) Make a view with given subviews arranged linearly (either horizontally or vertically)
//
// UIView+ViewArranging.h
// Created by on 15/05/2012.
//
#import <UIKit/UIKit.h>
typedef enum {
ViewArrangingDirectionHorizontal,
ViewArrangingDirectionVertical
}ViewArrangingDirection;
@interface UIView (ViewArranging)
// Creates a new view and adds the subviews to it either in the given direction.
// The returned view is just big enough to enclose the given views.
// Any views that are smaller than the parents size
// will be centered either horizontally or vertically
+ (UIView*) viewWithDirection:(ViewArrangingDirection)viewArrangingDirection
subviews:(UIView *)firstSubview, ...NS_REQUIRES_NIL_TERMINATION;
@end
//
// UIView+ViewArranging.m
// Created by on 15/05/2012.
//
#import "UIView+ViewArranging.h"
@implementation UIView (ViewArranging)
+ (UIView*) viewWithDirection:(ViewArrangingDirection)viewArrangingDirection
subviews:(UIView *)firstSubview, ...NS_REQUIRES_NIL_TERMINATION
{
NSMutableArray* subviews = [NSMutableArray arrayWithCapacity:10];
float totalWidth = 0;
float totalHeight = 0;
float maxWidth = 0;
float maxHeight = 0;
va_list args;
va_start(args, firstSubview);
for (UIView *subview = firstSubview; subview != nil; subview = va_arg(args, UIView*))
{
float width = subview.frame.size.width;
float height = subview.frame.size.height;
totalWidth += width;
totalHeight += height;
maxWidth = MAX(maxWidth, width);
maxHeight = MAX(maxHeight, height);
[subviews addObject:subview];
}
va_end(args);
UIView* view = nil;
if (viewArrangingDirection == ViewArrangingDirectionHorizontal) {
view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, totalWidth, maxHeight)];
} else {
view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, maxWidth, totalHeight)];
}
__block float totalOffset = 0;
[subviews enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
UIView* subview = obj;
CGRect frame = subview.frame;
if (viewArrangingDirection == ViewArrangingDirectionHorizontal) {
frame.origin.x = totalOffset;
totalOffset += frame.size.width;
frame.origin.y = (maxHeight - frame.size.height) / 2;
} else {
frame.origin.y = totalOffset;
totalOffset += frame.size.height;
frame.origin.x = (maxWidth - frame.size.width) / 2;
}
subview.frame = frame;
[view addSubview:subview];
}];
return view;
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment