ビューのサイズを変更せずに、次のコードで UIView の位置を変更します。
CGRect f = aView.frame;
f.origin.x = 100; // new x
f.origin.y = 200; // new y
aView.frame = f;
ビューの位置だけを変更する簡単な方法はありますか?
aView.center = CGPointMake(150, 150); // set center
また
aView.frame = CGRectMake( 100, 200, aView.frame.size.width, aView.frame.size.height ); // set new position exactly
また
aView.frame = CGRectOffset( aView.frame, 10, 10 ); // offset by an amount
編集:
これはまだコンパイルしていませんが、動作するはずです:
#define CGRectSetPos( r, x, y ) CGRectMake( x, y, r.size.width, r.size.height )
aView.frame = CGRectSetPos( aView.frame, 100, 200 );
私も同じ問題を抱えていました。それを修正する単純な UIView カテゴリを作成しました。
.h
#import <UIKit/UIKit.h>
@interface UIView (GCLibrary)
@property (nonatomic, assign) CGFloat height;
@property (nonatomic, assign) CGFloat width;
@property (nonatomic, assign) CGFloat x;
@property (nonatomic, assign) CGFloat y;
@end
.m
#import "UIView+GCLibrary.h"
@implementation UIView (GCLibrary)
- (CGFloat) height {
return self.frame.size.height;
}
- (CGFloat) width {
return self.frame.size.width;
}
- (CGFloat) x {
return self.frame.origin.x;
}
- (CGFloat) y {
return self.frame.origin.y;
}
- (CGFloat) centerY {
return self.center.y;
}
- (CGFloat) centerX {
return self.center.x;
}
- (void) setHeight:(CGFloat) newHeight {
CGRect frame = self.frame;
frame.size.height = newHeight;
self.frame = frame;
}
- (void) setWidth:(CGFloat) newWidth {
CGRect frame = self.frame;
frame.size.width = newWidth;
self.frame = frame;
}
- (void) setX:(CGFloat) newX {
CGRect frame = self.frame;
frame.origin.x = newX;
self.frame = frame;
}
- (void) setY:(CGFloat) newY {
CGRect frame = self.frame;
frame.origin.y = newY;
self.frame = frame;
}
@end
UIView にもcenter
プロパティがあります。サイズを変更するのではなく位置を移動したいだけの場合は、それを変更するだけです-例:
aView.center = CGPointMake(50, 200);
それ以外の場合は、投稿した方法で行います。
ここで大いに役立ったgcampの回答で同様のアプローチ(カテゴリも使用)を見つけました。あなたの場合、次のように簡単です:
aView.topLeft = CGPointMake(100, 200);
ただし、たとえば、別のビューで水平方向と左側を中央に配置したい場合は、次のように簡単にできます。
aView.topLeft = anotherView.middleLeft;
Autolayout を使用している場合、選択した回答のソリューションは機能しません。ビューに Autolayout を使用している場合は、この回答をご覧ください。
aView.frame = CGRectMake(100, 200, aView.frame.size.width, aView.frame.size.height);
Swift 3は「Make」を受け入れないため、探している人のためのSwift 3の回答は次のとおりです。
aView.center = CGPoint(x: 200, Y: 200)