hachinoBlog

hachinobuのエンジニアライフ

座標をオフセット指定で操作できるCGRectOffset

経緯

下記のように赤いViewのスグ隣に青いViewを配置したいとする。

f:id:hachinobu:20140209221339p:plain

今まではCGRectGet系メソッドを使って下記のようにやっていた。

//赤いViewの配置
UIView *redView = [[UIView alloc] initWithFrame:CGRectMake(60.0f, 150.0f, 100.0f, 100.0f)];
redView.backgroundColor = [UIColor redColor];
[self.view addSubview:redView];

//青いViewの配置
UIView *blueView = [[UIView alloc] initWithFrame:(CGRect){ CGPointZero, CGSizeMake(100.0f, 100.0f) }];
blueView.backgroundColor = [UIColor blueColor];
//CGRectGetを使って赤いViewの座標をもとに配置座標を取得
blueView.frame = (CGRect) { CGPointMake(CGRectGetMaxX(redView.frame), CGRectGetMinY(redView.frame)), blueView.frame.size };
[self.view addSubview:blueView];

しかしこの場合は下記のようにCGRectOffset(CGRect rect, CGFloat dx, CGFloat dy)を使った方が簡単にできる。

//赤いViewの配置
UIView *redView = [[UIView alloc] initWithFrame:CGRectMake(60.0f, 150.0f, 100.0f, 100.0f)];
redView.backgroundColor = [UIColor redColor];
[self.view addSubview:redView];

//青いViewの配置
UIView *blueView = [[UIView alloc] initWithFrame:(CGRect){ CGPointZero, CGSizeMake(100.0f, 100.0f) }];
blueView.backgroundColor = [UIColor blueColor];
//CGRectOffsetで青いViewの配置座標を指定
blueView.frame = CGRectOffset(redView.frame, CGRectGetWidth(redView.frame), .0f);
[self.view addSubview:blueView];

使い方

CGRectOffset(CGRect rect, CGFloat dx, CGFloat dy)

第一引数にターゲットのRectを指定して、第二引数にその座標からX軸にどれだけ移動させるか、第三引数にY軸にどれだけ移動させるか指定するだけ。

これを使えば簡単にあるViewの隣にViewを配置したりできる。