橫豎屏切換,視圖亂了怎麼辦?
首先,我們必須瞭解一下下列4種狀態,它們被用來描述裝置旋轉方向:
UIInterfaceOrientationLandscapeLeft |
向左,即HOME鍵在右 |
UIInterfaceOrientationLandscapeRight |
向右,即HOME鍵在左 |
UIInterfaceOrientationPortrait |
正立,即HOME鍵在下 |
UIInterfaceOrientationPortraitUpsideDown |
倒立,即HOME鍵在上 |
對於旋屏的處理,大致分為如下幾種情況和思路:
也許,你不需要旋屏支援,而希望鎖定螢幕
-(BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation{return NO;}
也許,你需要支援旋屏,或者支援部分方向的旋屏
-(BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation { return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);}
也許,你的view有張背景圖,旋屏時系統協助你展開了圖片,但是卻沒有管你的其它組件,比如button,你希望直接改變button的大小和位置
-(void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration{ if (UIInterfaceOrientationIsPortrait(toInterfaceOrientation)) { NSLog(@"現在是豎屏"); [btn setFrame:CGRectMake(213, 442, 340, 46)]; } if (UIInterfaceOrientationIsLandscape(toInterfaceOrientation)) { NSLog(@"現在是橫屏"); [btn setFrame:CGRectMake(280, 322, 460, 35)]; }}
也許,你並不希望用絕對座標去約束控制項,而是希望讓它通過旋轉自己適應螢幕的旋轉
- (void)viewDidLoad{ [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. UIDevice *device = [UIDevice currentDevice]; [device beginGeneratingDeviceOrientationNotifications]; //利用 NSNotificationCenter 獲得旋轉訊號 UIDeviceOrientationDidChangeNotification NSNotificationCenter *ncenter = [NSNotificationCenter defaultCenter]; [ncenter addObserver:self selector:@selector(orientationChanged) name:UIDeviceOrientationDidChangeNotification object:device];}- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation{ return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);}-(void)rotation_btn:(float)n{ UIButton *robtn = self.btn; robtn.transform = CGAffineTransformMakeRotation(n*M_PI/180.0);}-(void)orientationChanged{ UIDeviceOrientation orientaiton = [[UIDevice currentDevice] orientation]; switch (orientaiton) { caseUIDeviceOrientationPortrait: [self rotation_btn:0.0]; break; caseUIDeviceOrientationPortraitUpsideDown: [self rotation_btn:90.0*2]; break; caseUIDeviceOrientationLandscapeLeft: [self rotation_btn:90.0*3]; break; caseUIDeviceOrientationLandscapeRight: [self rotation_btn:90.0]; break; default: break; }}
也許,你需要autoresizesSubviews = YES
也許,你希望橫豎屏有不同的布局效果,需要準備2份Subview,在不同狀態去替換
當然不要忘記,需要調節設定圖示中的1、2處,
來協助我們完成自己想要的適應效果。Example 動畫呈現的很清晰,^_^ 我就不再囉嗦了。