资产目录中的横向与纵向背景图像

我有一个用例,似乎陷入资产目录和大小类别之间的裂缝。 我的通用应用程序需要横向和纵向不同的全屏幕背景图像,横向仅支持iPad和iPhone 6。

由于我无法将横向图像添加到新图像集的资产目录,因此我目前的解决scheme如下所示(支持iOS 7和8):

// permit landscape mode only for iPads & iPhone 6 (would prefer to use size classes, but...?) override func shouldAutorotate() -> Bool { let size = view.frame.size let maxv = max(size.width, size.height) return ((maxv > 700.0) || (maxv == 512.0)) ? true : false } // this will be triggered only for iOS 7, as long as viewWillTransitionToSize:withTransitionCoordinator: is also implemented! override func willRotateToInterfaceOrientation(toInterfaceOrientation: UIInterfaceOrientation, duration: NSTimeInterval) { adjustToOrientation(toInterfaceOrientation) } // this will be triggered only for iOS 8 override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) { let orientation = UIApplication.sharedApplication().statusBarOrientation // need to reverse the sense of the orientation here; Application still has the previous orientation switch orientation { case .Portrait, .PortraitUpsideDown: adjustToOrientation(.LandscapeLeft) case .LandscapeLeft, .LandscapeRight: adjustToOrientation(.Portrait) default: adjustToOrientation(.Portrait) } } func adjustToOrientation(newInterfaceOrientation: UIInterfaceOrientation) { let size = view.frame.size // rotation already permitted only for iPad & iPhone 6, but need to know which one (size classes useless here?) switch (max(size.width, size.height)) { case 1024.0: if UIInterfaceOrientationIsLandscape(newInterfaceOrientation) { backgroundImage.image = UIImage(named: "Background-Landscape@2x~ipad.png") } else { backgroundImage.image = UIImage(named: "Background@2x~ipad.png") } case 736.0: if UIInterfaceOrientationIsLandscape(newInterfaceOrientation) { backgroundImage.image = UIImage(named: "Background-Landscape@3x~iphone.png") } else { backgroundImage.image = UIImage(named: "Background@3x~iphone.png") } case 512.0: if UIInterfaceOrientationIsLandscape(newInterfaceOrientation) { backgroundImage.image = UIImage(named: "Background-Landscape~ipad.png") } else { backgroundImage.image = UIImage(named: "Background~ipad.png") } default: break } } 

这工作,但似乎脆弱。 是否有一种更正确的方式来识别设备是否支持Landscape中的常规尺寸类别,然后才能处于横向模式? 或者我错过了一些方式来指定一个图像集的景观等值?

您可以在资产目录中使用尺寸类别,也可以有两个图像集:一个用于纵向模式,另一个用于空间模式。 然后您可以通过资产名称访问图像。 这会减less你的代码一点。 但是,我build议在所有可能的地方使用尺寸类的cosider。

所以最终的解决scheme是:

– 将图像资产上的Width属性设置为Any + Regular,并为iPhone 6+和iPad添加一对横向图像,UIImage自动完成其余

– 一个更优雅的方式,只允许这两个设备,在iOS 7和iOS 8的旋转:

 override func shouldAutorotate() -> Bool { let scale = UIScreen.mainScreen().scale let idiom = UIDevice.currentDevice().userInterfaceIdiom return ((idiom == .Pad) || (scale > 2.0)) ? true : false } 

因此,所有的上述代码5行!