在viewDidLoad上动态确定viewcontroller的视图大小

时间:2014-01-17 19:34:24

标签: ios iphone objective-c

我已经搜索了很多关于如何在viewDidLoad方法中动态确定实际视图大小的搜索。

这是我的方法,它似乎适用于iOS6和iOS7,同时具有横向和纵向模式。

有更好的解决方案吗?

这是我的代码:

- (CGSize)actualSize {
    CGFloat widht;
    CGFloat height;

    // Determin height and widht
    UIDeviceOrientation orientation = [[UIDevice currentDevice] orientation];
    if (orientation == UIDeviceOrientationLandscapeRight ||  orientation == UIDeviceOrientationLandscapeLeft) {
        widht = kHeightSelfView;
        height = kWidthSelfView;
    } else {
        widht = kWidthSelfView;
        height = kHeightSelfView;
    }

    // Determin navigationbar height
    CGFloat navigationBarHeight = self.navigationController.navigationBarHidden ? .0f : (MIN(self.navigationController.navigationBar.frame.size.height, self.navigationController.navigationBar.frame.size.width));

    // Determin navigationbar height
    CGFloat statusbarHeight = [DeviceCompatibility isIOS7] ? (MIN(SharedApplication.statusBarFrame.size.width, SharedApplication.statusBarFrame.size.height)) : .0f;

    return CGSizeMake(widht, height - navigationBarHeight - statusbarHeight);
}

2 个答案:

答案 0 :(得分:0)

通常,您应该只在viewWillAppear中执行基于视图的几何体。您的视图框架尚未在viewDidLoad中设置,但在调用viewWillAppear之前将正确设置。

答案 1 :(得分:-1)

而不是挑选高度和宽度,您可以选择这样的视图框架:

// Adjusts the frame of the child view.
    CGRect frame = self.view.frame;
    CGRect linkedFrame = scene.view.frame;
    linkedFrame.origin.x -= frame.origin.x;
    linkedFrame.origin.y -= frame.origin.y;

然后你可以使它们变得灵活,以便它们能够正确调整大小:

// The scene's main view must be made flexible so it will resize properly
        // in the container.
        scene.view.autoresizingMask = (UIViewAutoresizingFlexibleWidth |
                                       UIViewAutoresizingFlexibleHeight);

如果这不是您需要的,请告诉我们。)