UIViewController 用代码改变方向

发布于 2024-12-10 04:07:01 字数 825 浏览 0 评论 0原文

为了更好的用户体验,我在代码中添加了以下内容:

if (allowLandscape) {
    return UIInterfaceOrientationIsLandscape(toInterfaceOrientation) || toInterfaceOrientation == UIInterfaceOrientationPortrait;
}
else {
    return toInterfaceOrientation == UIInterfaceOrientationPortrait;
}

因此,如果allowLandscape设置为YES,用户可以在所有典型的设备方向上使用该应用程序。但allowLandscape可以随时设置为NO,并且我想将UIViewController旋转回纵向。

以下代码仅在用户手动更改设备方向时才有效。因此,如果allowLandscape为YES,他就可以旋转设备,并且界面方向会跟随方向变化。但是,如果他保持横向方向,并且allowLandscape将设置为NO,他将保持横向方向,直到他将iPhone移动到纵向方向 - 现在,如果allowLandscape仍然为NO,则纵向方向无法更改。

我想要完成的是调用一些方法,强制 ViewController 用动画刷新它的方向(如果可能的话)。

调用该方法:

[[UIApplication sharedApplication] setStatusBarOrientation:UIInterfaceOrientationPortrait animated:YES];

只会改变状态栏,但界面仍保持之前的方向。我不想使用任何未记录的 API。

For better user experience I had the following in my code:

if (allowLandscape) {
    return UIInterfaceOrientationIsLandscape(toInterfaceOrientation) || toInterfaceOrientation == UIInterfaceOrientationPortrait;
}
else {
    return toInterfaceOrientation == UIInterfaceOrientationPortrait;
}

So, if allowLandscape is set to YES, user can play with the app in all typical device orientations. But allowLandscape can be set to NO anytime, and I want to rotate the UIViewController back to portrait orientation.

The following code only works if the user manually change the device orientation. So if allowLandscape was YES, he could rotate the device and the interface orientation followed the orientation change. But if he stays in landscape orientation, and allowLandscape will be set to NO, he stays in the landscape orientation, until he moves iPhone to the portrait orientation - now portrait orientation cannot be changed if the allowLandscape is still NO.

What I want to accomplish is to call some method, to force the ViewController to refresh it's orientation with animation if it's possible.

Calling the method:

[[UIApplication sharedApplication] setStatusBarOrientation:UIInterfaceOrientationPortrait animated:YES];

does only change the status bar, but the interface remains in the previous orientation. I don't want to use any undocumented APIs.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

伴我心暖 2024-12-17 04:07:01

解决方案如下:

    [[UIDevice currentDevice] endGeneratingDeviceOrientationNotifications];
    [[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications];

通过添加此代码,视图控制器再次询问应以哪个方向呈现其视图。

Here is the solution:

    [[UIDevice currentDevice] endGeneratingDeviceOrientationNotifications];
    [[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications];

By adding this code, view controller asks again, in which orientation should it present its view.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文