2011-04-30 42 views
1

我有一個具有圖像視圖和工具欄的UIViewController。我希望工具欄旋轉,但imageview保持原樣。這可能嗎?UIViewController autorotate一些組件?

+0

什麼是觸發旋轉?設備方向,設備指南針等? – dredful 2011-04-30 17:23:10

回答

2

是的,這是可能的,但需要手動處理旋轉事件。

在viewDidLoad中,添加

// store the current orientation 
currentOrientation = UIInterfaceOrientationPortrait; 
[[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications]; 
[[NSNotificationCenter defaultCenter] addObserver:self selector: @selector(receivedRotate:) name: UIDeviceOrientationDidChangeNotification object: nil]; 

if(currentOrientation != self.interfaceOrientation) { 
    [self deviceInterfaceOrientationChanged:self.interfaceOrientation]; 
} 

,並在控制器被刪除,不要忘記註銷事件。 然後添加一個方法旋轉:

// This method is called by NSNotificationCenter when the device is rotated. 
-(void) receivedRotate: (NSNotification*) notification 
{ 
    NSLog(@"receivedRotate"); 
    UIDeviceOrientation interfaceOrientation = [[UIDevice currentDevice] orientation]; 

    if(interfaceOrientation != UIDeviceOrientationUnknown) { 
     [self deviceInterfaceOrientationChanged:interfaceOrientation]; 
    } else { 
     NSLog(@"Unknown device orientation"); 
    } 
} 

終於rotate方法

- (void)deviceInterfaceOrientationChanged:(UIInterfaceOrientation)interfaceOrientation { 

    if(interfaceOrientation == currentOrientation) { 
     NSLog(@"Do not rotate to current orientation: %i", interfaceOrientation); 
    } else if(interfaceOrientation == UIInterfaceOrientationPortraitUpsideDown) { 
     NSLog(@"Do not rotate to UIInterfaceOrientationPortraitUpsideDown"); 
    } else if(interfaceOrientation == UIInterfaceOrientationLandscapeLeft) { 
     NSLog(@"Do not rotate to UIInterfaceOrientationLandscapeLeft"); 
    } else { 

     if(!isRotating) 
     { 
      isRotating = YES; 

      if(currentOrientation == UIInterfaceOrientationPortrait && interfaceOrientation == UIInterfaceOrientationLandscapeRight) { 
       NSLog(@"Rotate to landscape"); 

       // rotate to right top corner 
       [UIView beginAnimations:nil context:NULL]; 
       [UIView setAnimationDuration:0.5]; 

       // do your rotation here 

       [UIView setAnimationDelegate:self]; 
       [UIView setAnimationDidStopSelector:@selector(animationDoneShowCaption:finished:context:)]; 
       [UIView commitAnimations]; 


      } else if(currentOrientation == UIInterfaceOrientationLandscapeRight && interfaceOrientation == UIInterfaceOrientationPortrait) { 
       // etc 
      } 

      isRotating = NO; 
     } else { 
      NSLog(@"We are already rotating.."); 
     } 
    } 

    currentOrientation = interfaceOrientation; 
} 

請注意,我沒有在某些方向上允許旋轉時,你可能。

此外,您需要使您的組件可調整大小/能夠旋轉。

編輯考慮使用block-based動畫代替並在完成塊中設置isRotation = NO。