Skip to content

Instantly share code, notes, and snippets.

@taktamur
Created August 8, 2013 14:37
Show Gist options
  • Save taktamur/6185146 to your computer and use it in GitHub Desktop.
Save taktamur/6185146 to your computer and use it in GitHub Desktop.
UIScrollViewでハシゴ状レイアウトするカテゴリ拡張 ref: http://qiita.com/paming/items/a7f28c3eb23a7c297b27
//
// UIScrollView+LadderLayout.m
// UIScrollView+LadderLayout
//
#import "UIScrollView+LadderLayout.h"
// 便利拡張。UIViewのframe.{origin|size}へのアクセスを簡略化
@interface UIView(LadderLayout)
@property(readonly)CGFloat x;
@property(readonly)CGFloat y;
@property(readonly)CGFloat width;
@property(readonly)CGFloat height;
@end
@implementation UIView(LadderLayout)
-(CGFloat)x
{
return self.frame.origin.x;
}
-(CGFloat)y
{
return self.frame.origin.y;
}
-(CGFloat)width
{
return self.frame.size.width;
}
-(CGFloat)height
{
return self.frame.size.height;
}
@end
//梯子レイアウト本体
@implementation UIScrollView (LadderLayout)
-(void)layoutAndAddSubview:(NSArray *)views
{
// 配列に含まれるUIViewを整列
for(int i=0; i<views.count;i++ ){
NSRange range={0,i};
NSArray *layoutedViews = [views subarrayWithRange:range];
UIView *targetView = [views objectAtIndex:i];
// レイアウト済みの最後のViewの右側に、入れ込む隙間があるかどうかチェック
CGPoint nextStartPoint = CGPointMake(0,0);
if( i>0 ){
UIView *lastLayoutView = layoutedViews.lastObject;
nextStartPoint = CGPointMake(lastLayoutView.x+lastLayoutView.width,
lastLayoutView.y);
if( nextStartPoint.x + targetView.width > self.width ){
// はみ出してるので、次の段の左端に移動
nextStartPoint = CGPointMake(0,0);
for (UIView *v in layoutedViews) {
nextStartPoint.y = MAX(nextStartPoint.y, v.y + v.height);
}
}
}
// 移動先の場所が決まったので移動。
targetView.frame = CGRectMake(nextStartPoint.x,
nextStartPoint.y,
targetView.width,
targetView.height);
}
// 整列したUIViewをaddSubviewしていく
for(UIView *v in views){
[self addSubview:v];
}
// ScrollViewのcontentSizeを変更
CGFloat contentHeight=0;
for (UIView *v in views) {
contentHeight = MAX(contentHeight,v.y+v.height);
}
self.contentSize = CGSizeMake(self.width, contentHeight);
}
@end
-(void)viewWillAppear:(BOOL)animated
{
NSArray *colors = @[[UIColor redColor],
[UIColor orangeColor],
[UIColor blueColor],
[UIColor greenColor],
[UIColor grayColor],
[UIColor whiteColor],
[UIColor yellowColor],
[UIColor purpleColor] ];
srand((unsigned int)time(NULL)); // rand()の初期化
// ランダムサイズのUIViewを100個作って、
// 配列に入れておく。
NSMutableArray *views = [[NSMutableArray alloc]init];
for(int i=0; i<100; i++ ){
UIView *v = [[UIView alloc]init];
v.backgroundColor = [colors objectAtIndex:i%colors.count];
v.bounds = CGRectMake(0,0, 1+rand()%100,1+rand()%100);
[views addObject:v];
}
// 配列をScrollViewに叩き込んで整列させる。
UIScrollView *scrollView = (UIScrollView *)self.view;
[scrollView layoutAndAddSubview:views];
// Storyboardを使っている場合、AutoLayoutにチェックを入れると
// スクロールしないので注意。
// AutoLayout使うならこんな実装要らないだろうけど。
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment