在过去我使用Xcode 6.4时,我已经能够根据设备大小调整字体大小等内容。这是针对iOS 7的应用程序。现在对于Xcode 7和Swift 2,它只允许在iOS 8和更新的版本中这样做。它提示我用3个不同的选项来修复它。我不能让任何选择都起作用。是否有办法在Xcode 7中使用Swift 2为旧的iOS 7设备调整不同的设备?
在Xcode 6.4中,它看起来像这样在我的viewDidLoad()
:
if UIScreen.mainScreen().nativeBounds.height == 1334.0 {
//Name Details
redLabel.font = UIFont (name: "Arial", size: 13)
yellowLabel.font = UIFont (name: "Arial", size: 13)
greenLabel.font = UIFont (name: "Arial", size: 13)
blueLabel.font = UIFont (name: "Arial", size: 13)
}
在Xcode 7和Swift 2中,它给我一个警告'nativeBounds' is only available on iOS 8.0 or newer
。然后提示用3种不同的可能的修复方法修复它:
1)如果我选择Fix-it Add 'if available' version check
它会这样做:
if #available(iOS 8.0, *) {
if UIScreen.mainScreen().nativeBounds.height == 1136.0 {
//Name Details
redKid.font = UIFont (name: "Arial", size: 13)
yellowKid.font = UIFont (name: "Arial", size: 13)
greenKid.font = UIFont (name: "Arial", size: 13)
blueKid.font = UIFont (name: "Arial", size: 13)
}
} else {
// Fallback on earlier versions
}
2)如果我选择Fix-it Add @available attribute to enclosing instance method
,它会这样做:
@available(iOS 8.0, *)
override func viewDidLoad()
如果我选择Fix-it Add @available attribute to enclosing class
,它会这样做:
@available(iOS 8.0, *)
class ViewController: UIViewController {
我怎么能解决这个问题,让它运行iOS7的目标和调整不同的设备屏幕尺寸?谢谢你。
我做了一些研究,发现我可以在viewDidLoad()
中使用let bounds = UIScreen.mainScreen().bounds
。然后我可以在bounds.size.height
的基础上设置font
和其他项目。例如:
if bounds.size.height == 568.0 { // 4" Screen
redLabel.font = UIFont (name: "Arial", size: 15)
} else if bounds.size.height == 667.0 { // 4.7" Screen
redLabel.font = UIFont (name: "Arial", size: 18)
}
为了找到每个设备的bounds.size.height
,我在viewDidLoad()
上做了一个print(bounds.size.height)
。
我可以为两个不同的设备指定并添加更多,比如iPhone 6 Plus和iPad Retina。当我将iOS Deployment Target
设置为iOS 7.0时工作
在运行时,使用UIScreen对象的bounds和scale属性来了解UIKit如何将显示呈现给你的应用程序,当你需要处理显示上的确切像素数时,使用nativeBounds和nativeScale。
https://developer.apple.com/library/archive/documentation/DeviceInformation/Reference/iOSDeviceCompatibility/Displays/Displays.html