首页 文章

仅从纵向和旋转后正确加载景观视图,为什么?

提问于
浏览
0

这里有新的iOS开发者 . 我有多个视图,需要以纵向和横向显示不同的图像 . 我目前已成功实现并且肖像图像加载正常,并且在旋转时,景观图像也可以正常加载 . 但是,如果设备处于横向,则切换到另一个视图,它会不正确地加载 - 错误的大小,分辨率,对齐等 . 我处理方向更改的代码如下:

- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation
    {
        if((self.interfaceOrientation == UIDeviceOrientationLandscapeLeft) || (self.interfaceOrientation == UIDeviceOrientationLandscapeRight))
        {
            _image1.image = [UIImage imageNamed:@"Landscape.png"];
        }
        else if((self.interfaceOrientation == UIDeviceOrientationPortrait) || (self.interfaceOrientation == UIDeviceOrientationPortraitUpsideDown))
        {
            _image1.image = [UIImage imageNamed:@"Portrait.png"];
        }
}

我相信这是因为该方法仅在旋转时调用 . 例如,如果我旋转不正确的初始横向视图,它会再次显示正确的图像 . 当初始方向是横向时,有没有办法让方法运行并加载正确的横向视图?或者强制显示正确图像的方法?非常感谢 .

1 回答

  • 0

    我最后通过添加一个方向检查器来解决这个问题 . 我在.h中添加了以下内容:

    @property (nonatomic, readonly) UIDeviceOrientation *orientation;
    

    然后我在viewDidLoad方法中将它添加到我的.m文件中:

    if(([[UIDevice currentDevice] orientation] == UIDeviceOrientationLandscapeLeft) || ([[UIDevice currentDevice] orientation] == UIDeviceOrientationLandscapeRight)) {
    _image1.image = [UIImage imageNamed:@"Landscape.png"];
    }
    

    这将检查初始方向是否为横向 . 如果是,则加载我的Landscape.png图像 . 否则,由于默认图像是我的Portrait.png(如故事板中所设置),如果方向已经是纵向,则会加载 . 干杯!

    编辑:不建议使用上述代码,因为在使用它时可能会遇到问题,例如使用方向锁定设备 . 我更改了它以检查状态栏的方向,而不是设备的方向,如下所示:

    if(([[UIApplication sharedApplication] statusBarOrientation] == UIInterfaceOrientationLandscapeLeft) || 
    ([[UIApplication sharedApplication] statusBarOrientation] == UIInterfaceOrientationLandscapeRight)) { 
    _image1.image = [UIImage imageNamed:@"Landscape.png"];
    }
    

    您不需要在.h中声明任何变量,只需在viewDidLoad方法中添加上述变量即可 .

相关问题