iPad Orientation Checking UIView Class?

瘦欲@ 提交于 2019-12-08 00:25:44

问题


I have a UIView class which I add to my main UIViewController and I need to check the orientation of the device (iPad) at the launch of the app, in the viewDidLoad method. However because the class is a UIView (not UIViewController) I can't use methods such as willAnimateRotationToInterfaceOrientation.

So I attempted to use this in my UIView class:

if (([[UIDevice currentDevice] orientation] == UIDeviceOrientationLandscapeLeft) ||
    ([[UIDevice currentDevice] orientation] == UIDeviceOrientationLandscapeRight)) {

However, testing with some breakpoints, whatever the orientation is, the of statement is never called, its skips right passed it. So what do you suggest I do to overcome this issue?

I need to somehow detect the orientation from the UIView class.

Thanks.


回答1:


Where are you placing the check? The location could easily explain why it's not being called. To get rotation info, you could register for a notification, or have your view controller call a method in your view. Sample code for the latter:

// ViewController.m
- (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration {
    [self.customView willRotateToOrientation:toInterfaceOrientation];
}

// CustomView.m
- (void)willRotateToOrientation:(UIInterfaceOrientation)newOrientation {
    // Handle rotation
}

The view controller method is one you override; the view's method should be declared in a header.

Update: Alternatively, you can find out the rotation in the controller's `viewWillAppear':

// ViewController.m
- (void)viewWillAppear {
    [self.customView willRotateToOrientation:[[UIDevice currentDevice] orientation];
}

The method in your view will be called accordingly.




回答2:


One thing you can to is to register for orientation notification from NSNotificationCenter:

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

...

- (void)orientationChanged:(NSNotification *)notification
{
    UIDeviceOrientation orientation = [[UIDevice currentDevice] orientation];
    // do things
}

This is however suboptimal since iPad may be laying flat on the table when app starts, and you'll get UIDeviceOrientationUnknown then. Been here, done that...

I ended up doing a trivial check like this:

BOOL landscape = self.bounds.size.width > self.bounds.size.height;
if (landscape)
    // landscape stuff
else
    // portrait stuff

But in my case the view changed aspect ratio upon rotation. If this is your case too, it should work fine.



来源:https://stackoverflow.com/questions/7779619/ipad-orientation-checking-uiview-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!