2010-07-31 44 views

回答

18

您可以通過IB完成此操作,以獲得具有縱向和橫向佈局的應用程序,也可以通過編程方式執行此操作。這是關於程序化的方式。

要獲得取向的變更通知,使用

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

,並添加這樣的函數(注意,這是從一個項目,很多線路copypasted被排除在外,則需要調整改造您的具體情況)

-(void)orientationChanged 
{ 
    UIDeviceOrientation o = [UIDevice currentDevice].orientation; 

    CGFloat angle = 0; 
    if (o == UIDeviceOrientationLandscapeLeft) angle = M_PI_2; 
    else if (o == UIDeviceOrientationLandscapeRight) angle = -M_PI_2; 
    else if (o == UIDeviceOrientationPortraitUpsideDown) angle = M_PI; 

    [UIView beginAnimations:@"rotate" context:nil]; 
    [UIView setAnimationDuration:0.7]; 
    self.rotateView.transform = CGAffineTransformRotate(
           CGAffineTransformMakeTranslation(
            160.0f-self.rotateView.center.x, 
            240.0f-self.rotateView.center.y 
           ),angle); 
    [UIView commitAnimations]; 
} 

當您完成後,停止的通知,像這樣:

[[UIDevice currentDevice] endGeneratingDeviceOrientationNotifications]; 
[[NSNotificationCenter defaultCenter] removeObserver:self]; 
+0

嗯,這似乎並不完美,因爲它不會旋轉只是在另一個UIView內的UIImageView/UIView。相反,它旋轉整個UIView不只是子視圖。 – Joshua 2010-07-31 13:29:57

+0

然後使'self.rotateView'成爲您想要旋轉的子視圖。 – mvds 2010-08-02 11:13:18

+3

你應該使用'M_PI_2'而不是'M_PI/2.0f' – 2011-06-30 17:16:37