0
votes

I created a custom UIView and place it into a viewcontroller, I want to place it in the center of all Device (Ipad, Iphone)

so I do this

CGRect screenRect = [[UIScreen mainScreen] bounds];

self.center = CGPointMake((screenRect.size.height/2),(screenRect.size.width/2));

But it only work with Ipad/lanscape

How can I layout this view in center screen off all device , all orientation

2

2 Answers

1
votes

it not good practice, when view is self-positioning, you should do this from yours ViewController, for example in viewWillAppear, check, is yours viewControllers view is fullScreen and do this:

CGRect rect = [self.view bounds];

self.yoursView.center = CGPointMake((rect.size.width/2),(rect.height./2));
0
votes

Not sure if my answer is what you're looking for, but the way I see it you must set the view controller view's center as the center of the custom view. This should happen in every orientation.

Specifically, let's assume that you have a custom view named testView.

Initially upon creation you write:

self.testView.center = self.view.center;

A practical way that works in both iOS 8 and prior versions is to observe for the UIDeviceOrientationDidChangeNotification notification and be informed when the orientation of the device gets changed. Then you can set the center of the custom view again as shown above.

For example, in the viewDidLoad method make your class observe for the above notification:

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleOrientationChangeWithNotification:) name:UIDeviceOrientationDidChangeNotification object:nil];

Next, declare either privately or publicly the handleOrientationChangeWithNotification: method:

@interface ViewController ()

-(void)handleOrientationChangeWithNotification:(NSNotification *)notification;

@end

Finally, implement it as follows:

-(void)handleOrientationChangeWithNotification:(NSNotification *)notification{
    self.testView.center = self.view.center;
}

Now, every time that the orientation is changed, the custom view will be positioned to the center of the screen.

Hope that helps you.