Search code examples
iosswiftuiimageviewnslayoutconstraint

UIImageView width in viewDidLayoutSubviews is 1000?


I have an UIview that on top of itself has an UIImageView. I want both to be rounded so I wrote these lines of code:

override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()

        // make rounded profile image
        self.avatarPlaceholderView.layer.masksToBounds = true
        self.avatarPlaceholderView.layer.cornerRadius = self.avatarPlaceholderView.frame.width / 2.0
        self.avatarImageView.layer.masksToBounds = true
        self.avatarImageView.layer.cornerRadius = self.avatarImageView.frame.width / 2.0
    }

On paper everything should work fine, but it isn't. While UIView becomes rounded, UIImageView isn't shown at all. Further investigation showed that self.avatarPlaceholderView.frame.width returns proper width, but self.avatarImageView.frame.width returns width of 1000. What is even more strange if I comment last 2 lines, UIImageView will be visible, so constraints are set properly.

I have no idea why this is happening.

EDIT

Storyboard screen shots:

enter image description here enter image description here


Solution

  • Exact same thing happened to me as well. Had a UIImageView that was being converted to a circle post awakeFromNib via:

    self.iv.layer.masksToBounds = true;
    self.iv.layer.cornerRadius = self.iv.frame.width/2;
    

    Found the root cause and you're not going to like it - XCode 8 (surprise surprise).

    With absolutely no changes made the .xib that contained my imageview the corner radius modification worked fine. However, as soon as I opened this .xib file in XCode 8 (without changing anything), the image view circle modification no longer worked. This was because, as you noticed, the imageview's width was being detected as 1000 instead of the constant width constraint I had set to (32).

    As you probably know xcode changes .xib entries almost every time you open one, even if no modifications are performed. A lot of these are trivial IDE version tags but occasionally as with changes between major IDE version they alter non-trivial properties of the .xib for "compatibility" purposes.


    Workaroud: until Apple fixes this...

    1. Open your .xib file and perform any changes you need.
    2. Open the file inspector tab on the right hand side of Xcode
    3. Under the Interface Builder Document section, select "Opens in Xcode 7.x"
    4. This will prompt you to save and close the .xib. Do so and do not open the file again without performing these steps after each change
    5. Run your app again. 1000 width & height issue fixed!