在橫屏應用中,使用keyWindow添加一個視圖,切換設備橫屏方向,發現添加的視圖不會隨着變化方向。
並且只有Window的RootViewController可以監聽到屏幕旋轉變化。
[[UIApplicationsharedApplication].keyWindow addSubview:view];
解決方法如下:
定義RotateWindow繼承UIWindow,並重寫addSubview方法。AppDelegate中的window使用RotateWindow。
#define degreesToRadian(x) (M_PI * (x) / 180.0) - (void)addSubview:(UIView *)view { if ([self.subviews count] >= 1) { float angle = ([UIDevice currentDevice].orientation == UIDeviceOrientationLandscapeLeft)?90:-90; view.transform = CGAffineTransformMakeRotation(degreesToRadian(angle)); view.frame = CGRectOffset(self.frame, 0, 0); } [super addSubview:view]; }
定義RotateViewController作為window的RootViewController,並重寫以下方法
// 僅允許橫屏 - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation { // Return YES for supported orientations. return (interfaceOrientation == UIInterfaceOrientationLandscapeLeft || interfaceOrientation == UIInterfaceOrientationLandscapeRight); } // 設備旋轉時修改添加視圖方向 - (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration { UIWindow *window = [UIApplication sharedApplication].keyWindow; int i = 0; for (UIView *view in window.subviews) { if (i != 0) { CGAffineTransform transform = view.transform; transform = CGAffineTransformRotate(transform, degreesToRadian(180)); view.transform = transform; } i++; } }