簡體   English   中英

iOS:如何在viewWillAppear中找出當前方向?

[英]iOS: How do I figure out the current orientation in viewWillAppear?

我有一個UIWebView ,我想根據它的縱向或橫向加載不同的URL。 如何在viewWillAppear找出我目前的方向?

使用UIApplication的statusBarOrientation屬性。 如果您使用設備方向,如果它是UIDeviceOrientationFaceUpUIDeviceOrientationFaceDown ,則可能會遇到問題。

UIInterfaceOrientation orientation = [UIApplication sharedApplication].statusBarOrientation;
if (UIInterfaceOrientationIsLandscape(orientation))
{
   // Do something when in landscape
}
else
{
   // Do something when in portrait
}
UIDeviceOrientation getCurrentOrientation() {
  UIDevice *device = [UIDevice currentDevice];
  [device beginGeneratingDeviceOrientationNotifications];
  UIDeviceOrientation currentOrientation = device.orientation;
  [device endGeneratingDeviceOrientationNotifications];

  return currentOrientation;
}

您可以將UIDeviceOrientation轉換為UIInterfaceOrientation

當應用加載時,它不知道它當前的方向 -

UIInterfaceOrientation orientation = [[UIDevice currentDevice] orientation];
if (orientation == UIDeviceOrientationPortrait) {
    NSLog(@"portrait");// only works after a rotation, not on loading app
}

旋轉設備后,您可以獲得正確的方向,但是當加載應用程序時,不改變方向,似乎使用[[UIDevice currentDevice] orientation]不知道當前方向。

所以你需要做兩件事 -

  1. 嘗試在plist文件中設置應用程序接受的設備方向
  2. 在你的UIViewControllers中,你需要覆蓋shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)方法,當應用程序應該rotate:時返回YES rotate:

如果相關調用的順序意味着你不能依賴於viewWillAppear具有正確值的interfaceOrientation那么 - 假設父視圖控制器旋轉 - 最安全的事情可能是self.parentViewController.interfaceOrientation 如果沒有你可以嘗試從[[UIDevice currentDevice] orientation]做出第一個假設,這可能並不總是100%的錢(例如,如果你的應用程序啟動時設備平躺在桌子上),但很可能會給出你總是假設肖像是一個更好的猜測。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM