【问题标题】:UIView subview of UIWindow doesn't rotateUIWindow 的 UIView 子视图不旋转
【发布时间】:2012-01-05 04:14:08
【问题描述】:

我将UIView 添加到UIWindow,这不是keyWindow。我希望UIView 在设备旋转时旋转。 我需要设置窗口或视图的任何特殊属性吗?目前视图没有旋转。

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

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

【问题讨论】:

    标签: ios uiview uiwindow device-orientation


    【解决方案1】:

    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 或编写您的逻辑。

    【讨论】:

    • 我遇到了类似的问题——UIWindow 及其视图似乎没有旋转——而且这个解决方案似乎对我不起作用。我使窗口的 rootViewController 成为成功旋转其子视图的控制器,但窗口的子视图根本不旋转。
    • 他们不应该,因为他们没有附加到 UIViewController 并且只有 UIViewController 管理旋转
    • 这是一个很好的答案,谢谢。它在辅助窗口“Just Work”上进行旋转。要稍后从屏幕上删除窗口,只需将其 rootViewController 设置为 nil,并将对自身的引用也设置为,这样 ARC 就可以释放它。
    【解决方案2】:

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

    [[NSNotificationCenter defaultCenter] addObserver:self 选择器:@selector(didRotate:) 名称:UIDeviceOrientationDidChangeNotification 对象:nil];

    并创建了处理它的函数。

    【讨论】:

    • 我更喜欢“免费”获得轮换,而不是写didRotate
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-06
    相关资源
    最近更新 更多