Search code examples
iosswiftnslayoutconstraint

Rendered Size of Image Doesn't Match Frame Height (Swift)


I apologize in advance because this feels simple, but I've been trying to figure this out for a few days and can't figure it out after a lot of searching.

When I check the height of an image I've created programmatically with constraints the size doesn't match it's rendered size.

// Earth Image Setup
view.addSubview(earthImageView)
earthImageView.bottomAnchor.constraint(equalTo: loginTextViewTitle.topAnchor, constant: -standardSpacer).isActive = true
earthImageView.widthAnchor.constraint(equalToConstant: 500).isActive = true
earthImageView.heightAnchor.constraint(equalToConstant: 500).isActive = true
earthImageView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true

// Value of earthImageViewHeight is 276.  Why isn't it 500?
let earthImageViewHeight = earthImageView.frame.size.height

I'm seeing that the 276 comes from the pixels height of the original @1x image. However, how can I get the actual rendered height?

I thought it might have something to do with the points vs pixels, but that doesn't seem to be the case either.


Solution

  • The reason is the view isn't completely laid out yet. Once it's laid out then the you can use the constraints to set up other constraints, which is the question behind the question above.

    This post and this post give good explanations of what's going on and how to manage it. For my particular case calling...

    self.view.layoutIfNeeded()
    

    ...before my animation block started, and then re-adjusting the size of the image I was animating relative to another one that was already laid out.