在iOS 8上旋转后,窗口具有奇怪的框架和偏移

时间:2014-09-29 15:32:27

标签: ios rotation ios8 frame

在iOS 8上,当以横向模式启动应用程序时,我会在轮换后获得关键窗口框架的奇怪值:

// Before rotation (landscape)
{{0, 0}, {768, 1024}}

// After rotation (portrait)
{{-256, 0}, {1024, 768}}

代码:

NSLog(@"%@", NSStringFromCGRect(UIApplication.sharedApplication.keyWindow.frame));

X偏移来自何处,为什么帧值反转(横向模式下宽度= 768)?

1 个答案:

答案 0 :(得分:1)

我遇到了这个问题并使用fixedCoordinateSpace.bounds修复了它。这是一个简单的例子。

观察窗口中的状态栏更改。

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(statusBarFrameOrOrientationDidChanged) name:UIApplicationDidChangeStatusBarOrientationNotification object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(statusBarFrameOrOrientationDidChanged) name:UIApplicationDidChangeStatusBarFrameNotification object:nil];
        }
    return self;
}

旋转窗口并调整窗框大小。

- (void)statusBarFrameOrOrientationDidChanged {
    CGRect rect = ({
        CGRect rect;

        if ([[[UIDevice currentDevice] systemVersion] intValue] <= 7) {
            rect = [UIScreen mainScreen].bounds;

        } else {
            id<UICoordinateSpace> fixedCoordinateSpace = [UIScreen mainScreen].fixedCoordinateSpace;
            rect = fixedCoordinateSpace.bounds;
        }

        rect;
    });

    CGAffineTransform transform = CGAffineTransformMakeRotation(({
        CGFloat angle;

        switch ([UIApplication sharedApplication].statusBarOrientation) {
            case UIInterfaceOrientationPortraitUpsideDown:
                angle = M_PI;
                break;
            case UIInterfaceOrientationLandscapeLeft:
                angle = -M_PI_2;
                break;
            case UIInterfaceOrientationLandscapeRight:
                angle = M_PI_2;
                break;
            default:
                angle = 0.0f;
                break;
        }

        angle;
    }));

    if (!CGAffineTransformEqualToTransform(self.transform, transform)) {
        self.transform = transform;
    }

    if (!CGRectEqualToRect(self.frame, rect)) {
        self.frame = rect;
    }
}