Tabj Tabj - 2 months ago 5
Swift Question

CGRect not being applied

My code runs, but the problem is the

tab
image isn't being relocated to where I have it set in the code. It is staying where it is in the
viewController
and not getting any bigger or moving. I am trying to make it larger.

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

}
}

Answer Source

Both if conditions will be false and hence code will never be executed, this is because UIDevice.current.model will return either "iPhone", "iPod touch" or "iPad" and not the hardware model. The correct way to do it is:

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.

Instead a more robust method will be checking the screen size, iPhone 4s and lower models have a screen size of 320x480 point, the iPhone 5 have a screen size of 320x568 point, other devices have greater screen sizes.

Instead of targeting a certain device we will target a certain size. So if the screen height is greater than 480 point we run the code inside the first if block otherwise we run the code on the second block as follow:

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

But keep in mind that this is a very bad practice and you should use Auto Layout instead.