切換橫豎屏最直接的方式是調用device的setOrientation方法。但是從sdk3.0以后,這個方法轉為似有API,如果要上AppStore的話,要慎用!
if ([[UIDevice currentDevice] respondsToSelector:@selector(setOrientation:)]) {
[[UIDevice currentDevice] performSelector:@selector(setOrientation:)
withObject:(id)UIInterfaceOrientationLandscapeRight];
}
第二種方式是手動的設置界面元素的旋轉,包括狀態欄、導航欄和視圖。以下代碼為從豎屏設置為橫屏,坐標系是以豎屏的為基准,所以會出現負數的坐標值。
//設置狀態欄旋轉
[[UIApplication sharedApplication] setStatusBarOrientation:UIDeviceOrientationLandscapeRight animated:YES];
CGFloat duration = [UIApplication sharedApplication].statusBarOrientationAnimationDuration;
//設置旋轉動畫
[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:duration];
//設置導航欄旋轉
self.navigationController.navigationBar.frame = CGRectMake(-204, 224, 480, 32);
self.navigationController.navigationBar.transform = CGAffineTransformMakeRotation(M_PI*1.5);
//設置視圖旋轉
self.view.bounds = CGRectMake(0, -54, self.view.frame.size.width, self.view.frame.size.height);
self.view.transform = CGAffineTransformMakeRotation(M_PI*1.5);
[UIView commitAnimations];
來源: <http://blog.csdn.net/dickenslian/article/details/7407221>
*********************************************************************************************************************
一直遇到這個問題,今天終於找到了解決方法.
在我們的項目中經常遇到橫豎屏切換,而又有某個特定的界面必須是特定的顯示方式(橫屏或豎屏).這就需要如下的處理了.
強制轉成橫屏:
if ([[UIDevice currentDevice] respondsToSelector:@selector(setOrientation:)]) {
SEL selector = NSSelectorFromString(@"setOrientation:");
NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:[UIDevice instanceMethodSignatureForSelector:selector]];
[invocation setSelector:selector];
[invocation setTarget:[UIDevice currentDevice]];
int val = UIInterfaceOrientationLandscapeRight;
[invocation setArgument:&val atIndex:2];
[invocation invoke];
}
以上代碼支持ARC喲.
方法二: 通過判斷狀態欄來設置視圖的transform屬性。
- (void)deviceOrientationDidChange: (NSNotification *)notification
{
UIInterfaceOrientation interfaceOrientation = [[UIApplication sharedApplication] statusBarOrientation];
CGFloat startRotation = [[self valueForKeyPath:@"layer.transform.rotation.z"] floatValue];
CGAffineTransform rotation;
switch (interfaceOrientation) {
case UIInterfaceOrientationLandscapeLeft:
rotation = CGAffineTransformMakeRotation(-startRotation + M_PI * 270.0 / 180.0);
break;
case UIInterfaceOrientationLandscapeRight:
rotation = CGAffineTransformMakeRotation(-startRotation + M_PI * 90.0 / 180.0);
break;
case UIInterfaceOrientationPortraitUpsideDown:
rotation = CGAffineTransformMakeRotation(-startRotation + M_PI * 180.0 / 180.0);
break;
default:
rotation = CGAffineTransformMakeRotation(-startRotation + 0.0);
break;
}
view.transform = rotation;
}