开发者

Hide UIView on device rotation - doesn't work when device is horizontal

开发者 https://www.devze.com 2023-04-07 17:15 出处:网络
I\'m trying to hide an image in a view controller when the device is rotated.I\'m posting a notification in PlayerViewController and am listening for it in the app delegate, which is responsible for t

I'm trying to hide an image in a view controller when the device is rotated. I'm posting a notification in PlayerViewController and am listening for it in the app delegate, which is responsible for the bannerView:

- (void)orientationChanged:(NSNotification *)notification {     

  UIDeviceOrientation orientation = [[UIDevice currentDevice] orientation];

if ((orientation == UIDeviceOrientationLandscapeLeft) ||
    (orientation == UIDeviceOrientationLandscapeRight)) {

    bannerView.hidden = ([[self.navigationController visibleViewController] isKindOfClass:[PlayerViewController class]]) ? YES : NO;

} else {
    bannerView.hidden = NO;
}
}

The PlayerViewController sends a notification and the app delegate hides the bannerView. However, when the device is laid flat on a table, the image shows. Works fine when the device is held vertically but horizontally the image appears... odd.

Here is the code to send the notification:

 - (void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation
                                     duration:(NSTimeInterval)duration {

if (UIInterfaceOrientationIsLandscape(toInterfaceOrientation)) {
 ... hide other stuff in this view controller
 }

Any ideas why this odd behavior is occurring?

Just one tidbit more informa开发者_运维问答tion. In the simulator the image shows when the device is in upside-down orientation, even though I have:

- (BOOL)shouldAutorotateToInterfaceOrientation (UIInterfaceOrientation)interfaceOrientation
 {
if (interfaceOrientation == UIInterfaceOrientationLandscapeRight || interfaceOrientation == UIInterfaceOrientationLandscapeLeft || interfaceOrientation == UIDeviceOrientationPortrait) {
    return YES;
} else {
    return NO;
}
}


Your error might be happening because of when you're posting the notification.

willAnimateRotationToInterfaceOrientation is called before the orientation change takes place (hence the "will" in the method name). So if we're going from portrait to landscape, the current orientation may still be reported as portrait (it may not, it depends).

Now, the willAnimate... call returns the toInterfaceOrientation - the orientation that is going to happen.

You trigger your notification when you receive the willAnimate... call, and inside that notification call [[UIDevice currentDevice]orientation]: which will return portrait. Instead of requesting the orientation in your notification method you should instead pass the orientation provided in the willAnimate call.

If that wasn't clear, the one sentence summary: willAnimateRotationToInterfaceOrientation is called before the rotation changes.

0

精彩评论

暂无评论...
验证码 换一张
取 消