Reputation: 3541
I have a UIViewController subclass that instantiates a UIView subclass (let's call that viewA). Then, viewA will sometimes instantiate another UIView which we'll call viewB.
I want viewB to be centered within the view controller.
My question is, "What is a (correct) way of doing this?"
TIA
Upvotes: 0
Views: 78
Reputation: 38728
You have to be careful to not end up on a fraction of a point. On non-retina you need to be on full points but for retina you can be on 0.5
One way would be to use center
and then adjust
viewB.center = viewA.center;
viewB.frame = CGRectIntegral(viewB.frame);
Upvotes: 1
Reputation: 1129
There are many correct ways, but maybe the best one is to use the center-property:
[viewB setCenter: viewA.center];
Or maybe you need to use..
[viewB setCenter: viewA.navigationController.center];
Upvotes: 1
Reputation: 41652
viewB.frame = [MyClass centeredFrameForSize:desiredSize inRect:viewA.bounds];
+ (CGRect)centeredFrameForSize:(CGSize)size inRect:(CGRect)rect
{
CGRect frame;
frame.origin.x = rintf((rect.size.width - size.width)/2) + rect.origin.x;
frame.origin.y = rintf((rect.size.height - size.height)/2) + rect.origin.y;
frame.size = size;
return frame;
}
Upvotes: 0
Reputation: 2538
I don't know a shorter way to do it than this one:
CGFloat x = CGRectGetMidX(self.view.bounds) - viewBWidth / 2;
CGFloat y = CGRectGetMidY(self.view.bounds) - viewBHeight / 2;
viewB.frame = CGRectMake(x,y,viewBWidth,viewBHeight);
Upvotes: 0