概要
例えば frame 幅を10にしたいとき、
CGRect rect = view.frame;
rect.size.width = 10;
view.frame = rect;
という毎回のお約束がたるいので、それを1行で書けるようにするカテゴリを作りました。
bounds はあまりいじらないと思うので対応しません。
使い方
次のような感じに書けるようになります。
view.x = 10;
[view setX:10];
view.y = 20;
[view setY:10];
view.width = 100;
view.height = 200;
view.size = CGSizeZero;
[view setSize:CGSizeZero];
view.xRelative = -4;
view.heightRelative = 50;
UIViewAnimation Block 内でも使えます。
UIView+ViewFrame
setter と getter がプロパティに対応するように実装するだけです。
具体的には -setHoge:
-hoge
の対です。
.h
@interface UIView (ViewFrame)
// frame.origin を取得
- (CGPoint)origin;
- (CGFloat)x;
- (CGFloat)y;
// frame.size を取得
- (CGSize)size;
- (CGFloat)width;
- (CGFloat)height;
// frame.origin を設定
- (void)setOrigin:(CGPoint)p;
- (void)setX:(CGFloat)x;
- (void)setY:(CGFloat)y;
// frame.size を設定
- (void)setSize:(CGSize)s;
- (void)setWidth:(CGFloat)w;
- (void)setHeight:(CGFloat)h;
// frame.origin を相対的に設定
- (void)setOriginRelative:(CGPoint)p;
- (void)setXRelative:(CGFloat)x;
- (void)setYRelative:(CGFloat)y;
// frame.size を相対的に設定
- (void)setSizeRelative:(CGSize)s;
- (void)setWidthRelative:(CGFloat)w;
- (void)setHeightRelative:(CGFloat)h;
@end
.m
@implementation UIView (ViewFrame)
- (CGPoint)origin
{
return self.frame.origin;
}
- (CGFloat)x
{
return self.origin.x;
}
- (CGFloat)y
{
return self.origin.y;
}
- (CGSize)size
{
return self.frame.size;
}
- (CGFloat)width
{
return self.size.width;
}
- (CGFloat)height
{
return self.size.height;
}
// frame.origin を設定
- (void)setOrigin:(CGPoint)p
{
CGRect r = self.frame;
r.origin = p;
self.frame = r;
}
- (void)setX:(CGFloat)x
{
CGRect r = self.frame;
r.origin.x = x;
self.frame = r;
}
- (void)setY:(CGFloat)y
{
CGRect r = self.frame;
r.origin.y = y;
self.frame = r;
}
// frame.size を設定
- (void)setSize:(CGSize)s
{
CGRect r = self.frame;
r.size = s;
self.frame = r;
}
- (void)setWidth:(CGFloat)w
{
CGRect r = self.frame;
r.size.width = w;
self.frame = r;
}
- (void)setHeight:(CGFloat)h
{
CGRect r = self.frame;
r.size.height = h;
self.frame = r;
}
// frame.origin を相対的に設定
- (void)setOriginRelative:(CGPoint)p
{
CGRect r = self.frame;
CGPoint point = r.origin;
point.x += p.x;
point.y += p.y;
r.origin = point;
self.frame = r;
}
- (void)setXRelative:(CGFloat)x
{
CGRect r = self.frame;
CGPoint point = r.origin;
point.x += x;
r.origin = point;
self.frame = r;
}
- (void)setYRelative:(CGFloat)y
{
CGRect r = self.frame;
CGPoint point = r.origin;
point.y += y;
r.origin = point;
self.frame = r;
}
// frame.size を相対的に設定
- (void)setSizeRelative:(CGSize)s
{
CGRect r = self.frame;
r.size.width += s.width;
r.size.height += s.height;
self.frame = r;
}
- (void)setWidthRelative:(CGFloat)w
{
CGRect r = self.frame;
r.size.width += w;
self.frame = r;
}
- (void)setHeightRelative:(CGFloat)h
{
CGRect r = self.frame;
r.size.height += h;
self.frame = r;
}
@end