Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to center any subview horizontally in parent UIView but not vertically?

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

like image 541
Zeebok Avatar asked Apr 27 '15 16:04

Zeebok


3 Answers

Changing only the center like this may help

child.center = CGPointMake(CGRectGetMidX(parentView.bounds), child.center.y);
like image 165
Jaideep Nagra Avatar answered Nov 14 '22 09:11

Jaideep Nagra


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;
like image 37
ChrisH Avatar answered Nov 14 '22 08:11

ChrisH


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);
like image 1
Malav Soni Avatar answered Nov 14 '22 07:11

Malav Soni