我的代码正在运行,但问题是tab映像没有被重新定位到代码中设置它的位置。它呆在viewController的位置上,没有变大,也没有移动。我在试着让它变大。
@IBOutlet weak var tab: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
if UIDevice.current.model == "iPhone4,1" {
tab.frame = CGRect(x: 130, y: 122, width: 60, height: 60)
} else if UIDevice.current.model == "iPhone5,1" {
tab.frame = CGRect(x: 130, y: 171, width: 75, height: 75)
}
}发布于 2017-08-19 21:49:52
如果两个UIDevice.current.model条件都是假的,因此代码永远不会执行,这是因为将返回"iPhone“、"iPod触摸”或"iPad“,而不是硬件模型。正确的做法是:
override func viewDidLoad() {
super.viewDidLoad()
var systemInfo = utsname()
uname(&systemInfo)
// Retrive the device model
let model = Mirror(reflecting: systemInfo.machine).children.reduce("") { model, element in
guard let value = element.value as? Int8, value != 0 else { return model }
return model + String(UnicodeScalar(UInt8(value)))
}
if model == "iPhone4,1" {
tab.frame = CGRect(x: 130, y: 122, width: 60, height: 60)
} else if model == "iPhone5,1" {
tab.frame = CGRect(x: 130, y: 171, width: 75, height: 75)
}
}但这段代码只能在iPhone 4s或GSM iPhone 5上运行,而不会在其他设备上运行,如CDMA iPhone 5或iPhone 6或包括iPads在内的任何其他型号。
相反,更稳健的方法将是检查屏幕大小,iPhone 4s和较低型号的屏幕大小为320x480点,iPhone 5的屏幕大小为320x568点,其他设备的屏幕大小更大。
而不是针对特定的设备,我们将针对一定的规模。因此,如果屏幕高度大于480点,则在第一个if块内运行代码,否则将在第二个块上运行代码如下:
override func viewDidLoad() {
super.viewDidLoad()
if UIScreen.main.bounds.size.height > 480 {
tab.frame = CGRect(x: 130, y: 122, width: 60, height: 60)
} else {
tab.frame = CGRect(x: 130, y: 171, width: 75, height: 75)
}
}但是请记住,这是一个非常糟糕的实践,您应该使用自动布局。
发布于 2017-08-20 01:36:37
尝试以下几点:
extension UIDevice {
var modelName: String {
var systemInfo = utsname()
uname(&systemInfo)
let machineMirror = Mirror(reflecting: systemInfo.machine)
let identifier = machineMirror.children.reduce("") { identifier, element in
guard let value = element.value as? Int8, value != 0 else { return identifier }
return identifier + String(UnicodeScalar(UInt8(value)))
}
return identifier
}
}然后在这样的代码调用中:
if UIDevice.current.modelName == "iPhone4,1" {
tab.frame = CGRect(x: 130, y: 122, width: 60, height: 60)
} else if UIDevice.current.modelName == "iPhone5,1" {
tab.frame = CGRect(x: 130, y: 171, width: 75, height: 75)
}https://stackoverflow.com/questions/45773714
复制相似问题