7

我正在添加一个UIView不是UIWindowkeyWindow 的。我想UIView在设备旋转时旋转。我需要设置窗口或视图上的任何特殊属性吗?当前视图没有旋转。

我知道只有应用程序的第一个子视图keyWindow被告知设备旋转。作为测试,我将我的视图添加到keyWindow. 这会导致视图旋转。然而,keyWindow由于各种美学原因,作为 的第一个子视图的子视图的视图将不起作用。

另一种方法是观察视图中的设备方向变化并自己编写旋转代码。但是,如果可能的话,我想避免编写此代码(在我看来,有一个额外的窗口更干净)。

4

2 回答 2

7

UIView 不处理旋转, UIViewController 处理。因此,您只需要创建一个 UIViewController,它实现 shouldAutorotateToInterfaceOrientation 并将此控制器设置为您的 UIWindow 的 rootViewController

像这样的东西:

    UIViewController * vc = [[[MyViewController alloc] init] autorelease];

    vc.view.frame = [[UIScreen mainScreen] bounds];
    vc.view.backgroundColor = [UIColor colorWithWhite:0 alpha:0.4];

    //you vc.view initialization here

    UIWindow * window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    window.windowLevel = UIWindowLevelStatusBar;
    window.backgroundColor = [UIColor clearColor];
    [window setRootViewController:vc];
    [window makeKeyAndVisible];

我使用了这个 MyViewController,因为我希望它反映主应用程序的变化

    @interface MyViewController : UIViewController

    @end

    @implementation MyViewController

    - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation
    {
        UIWindow *window = ((UIWindow *)[[UIApplication sharedApplication].windows objectAtIndex:0]);
        UIViewController *controller = window.rootViewController;

        if (!controller) {
            NSLog(@"%@", @"I would like to get rootViewController of main window");
            return YES;
        }
        return [controller shouldAutorotateToInterfaceOrientation:toInterfaceOrientation];
    }
    @end

但是,如果您愿意,您始终可以对任何方向返回 YES 或编写您的逻辑。

于 2012-06-17T00:06:31.600 回答
2

您可以将以下代码添加到您的项目中

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didRotate:) name:UIDeviceOrientationDidChangeNotification object:nil];

并创建了处理它的函数。

于 2012-01-05T04:30:26.630 回答