2010-06-09 37 views
11

我正在基於每個頁面的UITabBarController和UIViewControllers的iPhone應用程序。該應用程序需要在縱向模式下只運行,所以每一個視圖控制器+應用程序委託去與這行代碼:手動檢測到風景旋轉

- (BOOL)shouldAutorotateToInterfaceOrientation: (UIInterfaceOrientation)interfaceOrientation { 
return (interfaceOrientation == UIInterfaceOrientationPortrait); 
} 

有一個視圖控制器,我想彈出一個UIImageView當iPhone是rotaed橫向左轉。圖像的設計看起來很美觀,但寬度和高度都是320x460(所以它的肖像)。

如何能/應該手動檢測這種類型的旋轉,只是在這個特定的視圖控制器中,沒有在整個視圖上自動旋轉?

托馬斯

UPDATE:

謝謝!

我加入這個監聽器在viewDidLoad中:

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

的didRotate看起來是這樣的:

- (void) didRotate:(NSNotification *)notification 

    { 
     UIDeviceOrientation orientation = [[UIDevice currentDevice] orientation]; 

     if (orientation == UIDeviceOrientationLandscapeLeft) 
     { 
      //your code here 

     } 
    } 

回答

20

我需要在一箇舊的項目 - 希望它仍然有效...

1)註冊通知:

[[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications]; 
[[NSNotificationCenter defaultCenter] addObserver:self 
             selector:@selector(detectOrientation) 
              name:UIDeviceOrientationDidChangeNotification 
              object:nil]; 

2)然後,你可以測試對旋轉上的變化:

-(void) detectOrientation { 
    if (([[UIDevice currentDevice] orientation] == UIDeviceOrientationLandscapeLeft) || 
     ([[UIDevice currentDevice] orientation] == UIDeviceOrientationLandscapeRight)) { 
     [self doLandscapeThings]; 
    } else if ([[UIDevice currentDevice] orientation] == UIDeviceOrientationPortrait || [[UIDevice currentDevice] orientation] == UIDeviceOrientationPortraitUpsideDown) { 
     [self doPortraitThings]; 
    } 
} 

希望幫助!

+3

謝謝!我添加了監聽器在viewDidLoad中: [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didRotate:)name:UIDeviceOrientationDidChangeNotification object:nil]; 的didRotate看起來像這樣: - (無效)didRotate:(NSNotification *)通知 {\t \t 取向UIDeviceOrientation = [[的UIDevice currentDevice]取向]; \t \t如果(方向== UIDeviceOrientationLandscapeLeft) \t { \t \t //你的代碼在這裏 \t}} 小 – 2010-06-09 11:59:27

+1

改進,使用常量UIDeviceOrientationDidChangeNotification而不是它的字符串值(這是@ 「UIDeviceOrientationDidChangeNotification」) – 2011-10-14 15:15:27

+0

不要忘記取消自己作爲活動的聽衆註冊... – aroth 2012-11-13 02:08:36

2

更好的代碼,以Comic Sans字體的答案是下面。他的代碼不會永遠正確觸發(在我的測試的時候只有80%)

-(void) detectOrientation { 
    if (UIDeviceOrientationIsLandscape([[UIDevice currentDevice] orientation])) { 
     [self setupForLandscape]; 
    } else if (UIDeviceOrientationIsPortrait([[UIDevice currentDevice] orientation])) { 
     [self setupForPortrait]; 
    } 
}