Automatically Sizing UIView after Adding to Window

前端 未结 6 911
孤街浪徒
孤街浪徒 2020-12-16 06:41

Note: This may be a duplicate of Subview Doesnt AutoSize When Added to Root View Controller


I have an iPad app that switches between different views in its mai

6条回答
  •  臣服心动
    2020-12-16 07:03

    This works, but it seems a little hacky:

    - (void)switchToViewController:(UIViewController *)viewController {
        if (viewController != currentViewController) {
            UIInterfaceOrientation orientation = currentViewController.interfaceOrientation;
            [currentViewController.view removeFromSuperview];
    
            currentViewController = viewController;
            UIView *view = viewController.view;
    
            // Set appropriate view frame (it won't be autosized by addSubview:)
            CGRect appFrame = [[UIScreen mainScreen] applicationFrame];
            if (UIInterfaceOrientationIsLandscape(orientation)) {
                // Need to flip the X-Y coordinates for landscape
                view.frame = CGRectMake(appFrame.origin.y, appFrame.origin.x, appFrame.size.height, appFrame.size.width);
            }
            else {
                view.frame = appFrame;
            }
    
            [window addSubview:view];
        }
    }
    

提交回复
热议问题