2014-12-05 68 views
-1

我有下面這段代碼,當設備改變自己的方向承認,如果方向是橫向向左或向右,他再次回到肖像:方向不第二次改變

[[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications]; 

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


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

    UIDevice * device = note.object; 

    if(device.orientation == UIDeviceOrientationLandscapeRight){ 


     [[UIDevice currentDevice] setValue: 
     [NSNumber numberWithInteger: UIInterfaceOrientationPortrait] 
            forKey:@"orientation"]; 
    } 

    if(device.orientation == UIDeviceOrientationLandscapeLeft){ 


     [[UIDevice currentDevice] setValue: 
     [NSNumber numberWithInteger: UIInterfaceOrientationPortrait] 
            forKey:@"orientation"]; 
    } 

} 

當我運行我的項目並將設備的方向改變爲左右風景,此代碼識別並將方向改爲肖像,但是如果我再次將設備旋轉到左右風景,則代碼不起作用,設備停留在風景模式下,爲什麼?以及如何解決這個問題?

回答

0

我不知道如果我是正確的,但試圖從viewWillAppear中

-(void)viewWillDisappear:(BOOL)animated 
{ 
    [super viewWillAppear] ; 
    [[NSNotificationCenter defaultCenter] 
addObserver:self selector:@selector(orientationChanged:) 
name:UIDeviceOrientationDidChangeNotification 
object:[UIDevice currentDevice]]; 

} 
0

解僱的通知,是更好的做法是註冊在viewWillAppear的通知,並在viewWillDisappear方法註銷。因此,只有當您的觀點呈現時纔會收到通知。

實現諸如:

-(void)viewWillAppear:(BOOL)animated 
{ 
    [super viewWillAppear] ; 
    [[NSNotificationCenter defaultCenter] 
    addObserver:self selector:@selector(orientationChanged:) 
    name:UIDeviceOrientationDidChangeNotification 
    object:[UIDevice currentDevice]]; 
} 

-(void)viewWillDisappear:(BOOL)animated 
{ 
    // Removing observer for lead created notification 
    [[NSNotificationCenter defaultCenter] removeObserver:self]; 
} 

如果UIDeviceOrientationDidChangeNotification沒有解決您的問題,請嘗試StatusBarOrientationNotification像如下。

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(statusBarOrientationChange:) name:UIApplicationDidChangeStatusBarOrientationNotification object:nil]; 

- (void)statusBarOrientationChange:(NSNotification *)note { 
    UIInterfaceOrientation orientation = [note.userInfo[UIApplicationStatusBarOrientationUserInfoKey] integerValue]; 

    // handle changes 
} 
0

而是與私人API和搞亂獲得從蘋果商店裏拒絕了,你應該使用標準方法,如supportedInterfaceOrientationsshouldAutorotate控制器只需鎖定旋轉。