Simple way to change the position of UIView?

2020-01-27 09:17发布

I change the position of a UIView with following codes without changing size of the view.

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

Is there more simple way to change only the view position?

标签: iphone uiview
12条回答
甜甜的少女心
2楼-- · 2020-01-27 09:58

Other way:

CGPoint position = CGPointMake(100,30);
[self setFrame:(CGRect){
      .origin = position,
      .size = self.frame.size
}];

This i save size parameters and change origin only.

查看更多
叼着烟拽天下
3楼-- · 2020-01-27 10:00

I found a similar approach (it uses a category as well) with gcamp's answer that helped me greatly here. In your case is as simple as this:

aView.topLeft = CGPointMake(100, 200);

but if you want for example to centre horizontal and to the left with another view you can simply:

aView.topLeft = anotherView.middleLeft;
查看更多
Juvenile、少年°
4楼-- · 2020-01-27 10:03

Here is the Swift 3 answer for anyone looking since Swift 3 does not accept "Make".

aView.center = CGPoint(x: 200, Y: 200)
查看更多
在下西门庆
5楼-- · 2020-01-27 10:06

The solution in the selected answer does not work in case of using Autolayout. If you are using Autolayout for views take a look at this answer.

查看更多
我命由我不由天
6楼-- · 2020-01-27 10:08
aView.center = CGPointMake(150, 150); // set center

or

aView.frame = CGRectMake( 100, 200, aView.frame.size.width, aView.frame.size.height ); // set new position exactly

or

aView.frame = CGRectOffset( aView.frame, 10, 10 ); // offset by an amount

Edit:

I didn't compile this yet, but it should work:

#define CGRectSetPos( r, x, y ) CGRectMake( x, y, r.size.width, r.size.height )

aView.frame = CGRectSetPos( aView.frame, 100, 200 );
查看更多
迷人小祖宗
7楼-- · 2020-01-27 10:08
aView.frame = CGRectMake(100, 200, aView.frame.size.width, aView.frame.size.height);
查看更多
登录 后发表回答