kitchen800
kitchen800

Reputation: 227

View changes size depending on device screen size, but should have a fixed size

enter image description here

I have created an orange circle using a UIView100 height and 100 width with a radius of 50. This was done in the 4 inch setup. When i move up to the 4.7inch or higher the circle becomes distorted. What do i do so that the circle doesn't get distorted when displayed on larger devices?

Upvotes: 2

Views: 2661

Answers (2)

rob mayoff
rob mayoff

Reputation: 386038

So I guess you used Xcode's “Reset to Suggested Constraints” option, like this:

reset to suggested constraints

When you do that, Xcode guesses what constraints you want. Unfortunately, in your case, it guessed wrong. It did create the centering constraints you wanted, but it did not create the width and height constraints you wanted. Instead it created leading edge and top edge constraints, like this:

edge constraints

So when you load your scene on a larger device, in order to satisfy those constraints, auto layout has to make the view larger, like this:

resized

To fix this, you need to delete the edge constraints:

deleting edge constraints

And add width and height constraints:

adding width and height constraints

So your final constraints on the subview look like this:

final constraints

With these constraints, when you load your scene on a larger device, the subview will stay centered and not change size:enter image description here

Upvotes: 6

Fernando Mazzon
Fernando Mazzon

Reputation: 3591

I'm betting you used a fixed corner radius to make a circular UIView (which would have a constraint for 1:1 aspect ratio too). Just make it so the radius of the corners is calculated somewhere where the right dimensions for the view can be known. viewDidLayoutSubviews is a good place as it'll take care of other resizes like screen rotation.

override func viewDidLayoutSubviews() {
    self.circleView.layer.cornerRadius = self.circleView.frame.size.width / 2 // Assumes width == height because of 1:1 aspect ratio constraint
}

Alternatively don't make the size of your view depend on the width or height of the screen (i.e. remove constraints to the sides, center it and give it a fixed width and height)

Upvotes: 1

Related Questions