Reputation: 732
I need movie player to be centered vertically.
moviePlayer.view.frame = CGRect(x: ???, y: self.view.frame.size.height/4, width: 200, height: 200)
I've tried self.view.frame.size.width/2
and self.view.center.x
.
How can i do it ?
Upvotes: 0
Views: 91
Reputation: 1038
Here are two programming idioms that you can use for centering a subview within it's super view. If you are writing a custom view, this code should go in that view's layoutSubviews
method. If this is part of a view controller, it should go in its viewDidLayoutSubviews
method.
Method 1: Setting the center
CGFloat x = CGRectGetMidX(superview.bounds);
CGFloat y = CGRectGetMidY(superview.bounds);
subview.center = CGPointMake(x, y);
Method 2: Setting the frame
CGFloat width = (... calculate subview width ...);
CGFloat height = (... calculate subview height ...);
CGFloat x = (CGRectGetWidth(superview.bounds) - width) / 2.0;
CGFloat y = (CGRectGetWidth(superview.bounds) - height) / 2.0;
subview.frame = CGRectMake(x, y, width, height);
Upvotes: 1
Reputation: 1407
You can just set center
property after setting frame.
moviePlayer.view.center = self.view.center;
One more to consider - if moviePlayer.view
is a subview of self.view
, don't use self.view.frame
. Consider using self.view.bounds
instead.
To center vertically
CGPoint center = self.view.center;
center.y = //whatever you need
moviePlayer.view.center = center;
Update
As @Antonio mentioned, it works only if self.view's top left corner is screen left top corner itself.
Better way
CGPoint center = CGPointMake(CGRectGetMidX(self.view.bounds), <#Whatever you need#>);
moviePlayer.view.center = center;
But still, I suggest using NSLayoutConstraints for greater good =)
Something to consider
However, setting frames that way isn't the best - you will be forced to calculate each view's position and size manualy. If your layout is plain, use autoresizingMask
and contentMode
. Like that
//after setting moviePlayer.view.frame
moviePlayer.view.autoresizingMask = UIViewAutoresizingNone;
self.view.contentMode = UIViewContentModeCenter;
In case, your content isn't simple enough, use NSLayoutConstraint
s. Also, using it you can center only by one axis (vertically or horizontally)
Upvotes: 1