32
32

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

UIViewのframe指定での移動をちょっとだけ楽にする

Posted at

iPhoneアプリを作ってる際によくUIViewを移動させることが多いです。(私だけかも知れません)

sizeを変更しないでx,y座標だけを変更する場合に

// UIViewの座標をx = 100, y = 50に動かしたい場合
UIView* view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 100, 100)];
view.frame = CGRectMake(100, 50, view.frame.size.width, view.frame.size.height);

と書けば動きますが、めんどくさい!(と思っても4回ぐらい上の用に書いてます。)

めんどくさいので思い腰を上げた結果
Category作って多少楽になりました。

// UIView+Util.h
@interface UIView (Util)
-(void) moveBy:(CGPoint) point;
-(void) moveTo:(CGPoint) point;
@end

// UIView+Util.m
-(void) moveBy:(CGPoint)point {
    self.frame = (CGRect){.origin = point, .size = self.frame.size};
}
-(void) moveTo:(CGPoint)point {
    CGPoint nowPoint = self.frame.origin;
    self.frame = (CGRect){.origin.x = nowPoint.x + point.x, .origin.y = nowPoint.y + point.y, .size = self.frame.size};
}

使い方は至って簡単

#import "UIView+Util.h"
UIView* view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 100, 100)];
[view moveBy:CGPointMake(100, 50)];

あーちょっと楽になった気がするー

32
32
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
32
32

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?