How to center any subview in its parent UIview only horizontally, not vertically. I tried child.center = parent.center
but it place my child view in the center of the parent view both horizontally and vertically. How can i align it in center just horizontally. Thanks
Asked
Active
Viewed 1.1k times
11

Zeebok
- 388
- 1
- 4
- 15
-
1Set only center.x and ignore y value – Jageen Apr 27 '15 at 16:12
-
center is a CGPoint. yous should just be able to set the x value of it to the parent views center x value – Steve Apr 27 '15 at 16:14
4 Answers
30
Changing only the center like this may help
child.center = CGPointMake(CGRectGetMidX(parentView.bounds), child.center.y);

Jaideep Nagra
- 519
- 3
- 13
-
Will you please tell me that is there any difference between child.center.y and child.origin.y. – Zeebok Apr 28 '15 at 07:05
-
1@ChrisH Yeah I made a mistake in the answer. Thanks for pointing it out. – Jaideep Nagra Apr 28 '15 at 07:30
-
@Zeebok center tells the center point of view in it's superview's coordinate system whereas origin tells location of view in it's superview coordinate system. For detailed description check this [stackoverflow](http://stackoverflow.com/questions/5361369/uiview-frame-bounds-and-center) question. – Jaideep Nagra Apr 28 '15 at 07:40
-
1@Jaideep np - you could also take this one step further and use `parent.center.x` as the first value. – ChrisH Apr 28 '15 at 16:17
2
You can't modify the x
property of the UIViewController
's center
directly, but you can do the following:
CGPoint center = child.center;
center.x = parent.center.x;
child.center = center;

ChrisH
- 4,468
- 2
- 33
- 42
-
Many Thanks Jaideep, your answer is superb. Your Answer is much easy to understand, but i am little bit confused. Jaideep also gave a good answer, i am confused which one should i accept. Your both are fabulous. – Zeebok Apr 28 '15 at 05:49
1
Try this,
subview.frame = CGRectMake(((parentView.frame.size.width/2)-(subview.frame.size.width/2)),subview.frame.origin.y,subview.frame.size.width,subview.frame.size.height);

Malav Soni
- 2,739
- 1
- 23
- 52
0
I needed to horizontally centre (but not vertically) a UIImageView for each different device size, so I used this, which worked well:
CGRect screenRect = [[UIScreen mainScreen] bounds];
[self.myImageView setCenter:CGPointMake(CGRectGetMidX(screenRect), self.myImageView.frame.origin.y + self.myImageView.frame.size.height/2)];

itsji10dra
- 4,603
- 3
- 39
- 59

JanB
- 904
- 9
- 14