Search code examples
iosswiftuiviewautolayout

Rounding views with Auto Layout?


I want to create circular views when using Auto Layout, due to this, I can't set specific radius values in my view.

I thought I had resolved this with the following code, but it doesn't execute on the view's first load for some reason and the view appears square until I push the view of the screen and bring it back (for example raising the keyboard and lowering it). Any idea why or how I can approach a fix?

 override func viewWillLayoutSubviews() {
    self.myProfileView.userImage.layer.cornerRadius = self.myProfileView.userImage.frame.size.width * 0.5
    self.myProfileView.userImage.layer.borderWidth = 2
    self.myProfileView.userImage.layer.borderColor = UIColor().appThemeColour().cgColor
}

Constraints:

userImage.snp.makeConstraints { (make) -> Void in
            make.centerX.equalTo(self)
            make.centerY.equalTo(self).multipliedBy(0.25)
            userImage.heightAnchor.constraint(equalTo: userImage.widthAnchor).isActive = true
            userImage.widthAnchor.constraint(equalTo: self.widthAnchor, multiplier: 0.40).isActive = true
        }

Before pushing the view on the screen when it first loads:

view is still square-shaped

After I open and close the keyboard pushing the view off and back on screen:

view is now rounded


Solution

  • You should run the rounding code in viewDidLayoutSubviews instead, which runs after the layout has correct frames.

    Also, execute layoutIfNeeded() for myProfileView before accessing its size.

    override func viewDidLayoutSubviews() {
        myProfileView.layoutIfNeeded()
    
        myProfileView.userImage.layer.cornerRadius = myProfileView.userImage.frame.size.width * 0.5
        myProfileView.userImage.layer.borderWidth = 2
        myProfileView.userImage.layer.borderColor = UIColor().appThemeColour().cgColor
    }