Coder221
Coder221

Reputation: 1433

Image dimensions changing on rotation

I have an image called sampleImage, and I am trying to stretch it along x and y axis, as follows when it is in landscape and it did not work at all

 override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator)
  {
   if (UIDevice.current.orientation == UIDeviceOrientation.portrait)
    {
     sampleImage.frame = CGRect(x: 0, y: 0, width: 220, height: 120)
    }
   else
    {
    sampleImage.frame = CGRect(x: 0.2, y: 0.2, width: 220, height: 120)
    }
 }

Then, I did in viewDidLayoutSubviews() as follows,

override func viewDidLayoutSubviews() {

    super.viewDidLayoutSubviews()

if (UIDevice.current.orientation == UIDeviceOrientation.portrait)
        {
         sampleImage.frame = CGRect(x: 0, y: 0, width: 220, height: 120)
        }
else
        {
        sampleImage.frame = CGRect(x: 0.2, y: 0.2, width: 220, height: 120)
        }
     }

This works if the device is in landscape, but once you rotate it to portrait and back, all the changes are gone.How to make sure that those dimensions stay same on rotation?

Upvotes: 1

Views: 332

Answers (1)

pacification
pacification

Reputation: 6018

Basically, it's all about constraints. First approach to solve your problem is to handle device rotation (good so answer) and change it manually via setNeedsUpdateConstratints method (another good so answer). This way good for heavy screen with complex changes with UI and constraints. In your case you better use specific constant for constraint base on device orientation that can be set in storyboard.

So, follow this steps:

Set Equal Heights and Equal Widths constraints to the UIImageView, then double click for Width Equals: 120 constraint:

enter image description here

Open View as: iPhone ... bottom bar:

enter image description here

Select specific device and landscape orientation at right side and hit the + before Constant at the right panel.

enter image description here

It will automatically set right Width and Height base on selected device and orientation, so you just need to enter the constant for this case. Run the project and see the result.

Portrait:

enter image description here

Landscape:

enter image description here

Note, also don't forget that different devices may have different size classes (compact x compact, compact x regular, etc.), so maybe you will need to add few more constants to handle this problem (see the table at the bottom of the article).

Finally, you solved the problem by working with storyboard, not programmatically. Pros of that - you code not grow up and not responsible for the UI things, cons - you should add the constant to every size class you want to use.

Upvotes: 3

Related Questions