Hobbyist
Hobbyist

Reputation: 16202

Full width view does not contain same frame width as parent

I'm having an issue where I have a UIImageView that spans the entire width of the screen using the following constraints.

The image assumes the width of the screen while gaining aspect ratio (in this case a square). The issue comes with when I started attempting to make a circle out of the image, that I noticed that my UIIMageView's frames do not have proper values.

You'll have to excuse to code below for not being in Objective-C as I'm using Java through RoboVM but with very little effort you can mentally convert the code to Objective-C as it's pretty straightforward.

public class MyViewController extends UIViewController {
    @IBOutlet private UIImageView myImageView;

    @Override public void viewDidLoad() {
        System.out.println("Image view width: " + myImageView.getFrame().getWidth());
        System.out.println("Superview width: " + this.getView().getFrame().getWidth());
    }
}

The results of running the application with this Controller shows the following:

Image view width: 240.0
Superview width: 320.0

When cutting the frame width of the image in half and applying that to the CALayer#cornerRadius property, the image does not make a complete circle, however when using half of the superviews width (Which is actually the size of the image) the result is a perfect circle.

Upvotes: 0

Views: 48

Answers (2)

Russell
Russell

Reputation: 5554

The reason you need the -20 margin is because your superview has a margin of 20, and the constraints are created by default to 'Relative to margin' - if you uncheck that, you can set the 'real' constraint - in this case zero rather than -20

If you select the constraint in the assistant editor, you will see the check box to toggle this value

Upvotes: 0

Eric Galluzzo
Eric Galluzzo

Reputation: 3241

In viewDidLoad, it has just loaded your view from the XIB or storyboard, not sized it yet. The size should be correct when viewWillAppear is called. So try putting your code in viewWillAppear and see if that helps.

Upvotes: 2

Related Questions