72

ビューのサイズを変更せずに、次のコードで UIView の位置を変更します。

CGRect f = aView.frame;
f.origin.x = 100; // new x
f.origin.y = 200; // new y
aView.frame = f;

ビューの位置だけを変更する簡単な方法はありますか?

4

13 に答える 13

229
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 );
于 2011-03-01T22:26:52.173 に答える
33

私も同じ問題を抱えていました。それを修正する単純な 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
于 2011-03-01T22:42:36.520 に答える
13

UIView にもcenterプロパティがあります。サイズを変更するのではなく位置を移動したいだけの場合は、それを変更するだけです-例:

aView.center = CGPointMake(50, 200);

それ以外の場合は、投稿した方法で行います。

于 2011-03-01T22:23:41.267 に答える
7

ここで大いに役立ったgcampの回答で同様のアプローチ(カテゴリも使用)を見つけました。あなたの場合、次のように簡単です:

aView.topLeft = CGPointMake(100, 200);

ただし、たとえば、別のビューで水平方向と左側を中央に配置したい場合は、次のように簡単にできます。

aView.topLeft = anotherView.middleLeft;
于 2013-01-25T17:39:21.717 に答える
6

Autolayout を使用している場合、選択した回答のソリューションは機能しません。ビューに Autolayout を使用している場合は、この回答をご覧ください。

于 2013-11-15T11:50:24.527 に答える
4
aView.frame = CGRectMake(100, 200, aView.frame.size.width, aView.frame.size.height);
于 2011-03-01T22:24:39.760 に答える
0

Swift 3は「Make」を受け入れないため、探している人のためのSwift 3の回答は次のとおりです。

aView.center = CGPoint(x: 200, Y: 200)
于 2017-01-09T06:16:25.907 に答える