在发布时检测界面方向的正确方法是什么?

Mar*_*ark 6 iphone orientation ipad

[问题更新]

所以这就是问题所在,我最终将其缩小到了这个范围.如果在所有方法中创建新的UIViewController

- (id)init;
- (void)loadView;
- (void)viewDidAppear:(BOOL)animated;
- (void)viewDidLoad;
(...)
Run Code Online (Sandbox Code Playgroud)

标准interfaceOrientation为Portrait,如果检测到横向模式,它将快速旋转到该方向.然后可以使用以下方法检测:

- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation;
Run Code Online (Sandbox Code Playgroud)

问题是在iPad上,很难为loadView(或其中一个)中的当前界面方向准备界面,因为它只返回Portrait.这会导致一些问题:

1)我希望我的内容在portait模式下重新加载,但不是在横向模式下.通常我会在loadView中放置一个if语句.如果处于纵向模式,请重新加载内容.但在这种情况下,它将始终返回纵向,因此始终加载内容.

2)我想使用'presentPopoverFromRect:inView:allowedArrowDirections:animated:' - 处于纵向模式的方法,以便在应用程序启动时自动显示弹出菜单.在纵向模式下启动时,这将使应用程序崩溃.原因:'弹出窗口无法从没有窗口的视图中呈现.'

唯一安全的假设是在'didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation'中,但如果它以纵向模式启动,则不会触发此方法.

// ----

更新(15.37)

'UIApplicationWillChangeStatusBarOrientationNotification'

仅在用户从纵向切换到横向(或反之亦然)时才会发布.如果接口是问题,那么通过观察该通知可以很容易地解决这个问题

if (UIDeviceOrientationIsPortrait(interfaceOrientation)) {
    // layout subviews for portrait mode
} else {
    // layout subviews for landscape mode
}
Run Code Online (Sandbox Code Playgroud)

但问题是,我想知道它在启动时以哪种模式确定我是否应该重新加载内容,我无法重新加载内容,当它切换到横向取消它时.

Mar*_*ams 8

试试[[UIApplication sharedApplication] statusBarOrientation].


Pas*_*cal 6

正确的方法是询问设备的方向,因为视图在技术上没有方向.;)

所以你的使用是正确的UIDevice.从文档中可以看出,在此信息正确之前,您首先需要生成设备方向通知.然后它将按照需要工作.

UIDevice *myDevice = [UIDevice currentDevice];
[myDevice beginGeneratingDeviceOrientationNotifications];
UIDeviceOrientation currentOrientation = [myDevice orientation];
[myDevice endGeneratingDeviceOrientationNotifications];
Run Code Online (Sandbox Code Playgroud)

注意:这将为您提供设备的当前方向.如果当前的可见/顶视图控制器并没有让旋转这个方向上,你将仍然获得当前设备方向,而不是最上面的视图控制器目前使用的一个.


问题更新后编辑:

你是对的,最顶层视图控制器的方向(对于子视图控制器正常工作)总是返回1(即UIInterfaceOrientationPortrait)loadView.但是willRotateToInterfaceOrientation:duration:之后会立即调用该方法,并且在那里传递的方向是正确的,因此您应该能够使用该方法.

- (void) willRotateToInterfaceOrientation:(UIInterfaceOrientation)toIfaceOrient
                                 duration:(NSTimeInterval)duration
Run Code Online (Sandbox Code Playgroud)