我的代码运行了,但问题是选项卡
图像没有被重新定位到我在代码中设置的位置。它停留在 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)
}
}
最佳答案
两个 if 条件都将为 false,因此代码永远不会执行,这是因为 UIDevice.current.model 将返回“iPhone” em>、“iPod touch” 或 “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)
}
}
But this code will run only on an iPhone 4s or a GSM iPhone 5 and will not run on other devices like: a CDMA iPhone 5 or an iPhone 6 or any other model including iPads.
更可靠的方法是检查屏幕尺寸,iPhone 4s 及更低型号的屏幕尺寸为 320x480 点,iPhone 5 的屏幕尺寸为 320x568> 一点,其他设备的屏幕尺寸更大。
我们不会针对特定设备,而是针对特定尺寸。因此,如果屏幕高度大于 480 点,我们将在第一个 if block 内运行代码,否则我们将在第二个 block 上运行代码,如下所示:
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)
}
}
但请记住,这是一个非常糟糕的做法,您应该使用 Auto Layout相反。
关于ios - CGRect 未应用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45773714/