CGRect 未被应用

CGRect not being applied

我的代码可以运行,但问题是 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)

    }
}

两个 if 条件都将为假,因此代码将永远不会被执行,这是因为 UIDevice.current.model 将 return "iPhone""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 块中的代码否则我们 运行 第二个块中的代码如下:

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

尝试以下操作:

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)
}