Search code examples
swiftuibuttonrounded-cornerscornerradius

Setting corner radius through viewDidAppear() or viewWillLayoutSubviews()?


In summary, setting the corner radii to get round left and right edges for my UIButtons in my application works by grabbing the buttons bounds and dividing the height by two in viewWillLayoutSubviews(). However, if I navigate to another screen via UIBarButtonItem(), rotate the device, and then navigate back to the screen with the UIButtons() they are NOT round. The corner radii are still based on the button dimensions from the previous orientaion. I tried to use viewDidAppear, but there is a second/noticable delay in setting the corner radii.

Is there anyway to speed the process up of viewDidAppear? I don't think viewWillAppear will work because the view controller isn't aware of the default (square) dimensions of the uibutton(s) I am changing.

The application I am working on is this:

Screenshots of my current application from loading screen to the point of the corner radius not being updated correctly


Solution

  • Use viewDidLayoutSubviews instead, because you'll have the updated bounds at that point, but not yet in viewWillLayoutSubviews.

    Or I might suggesting have a button subclass that does the rounding within its own layoutSubviews, freeing your view controller from having to iterate through buttons and rounding them.

    For example:

    @IBDesignable
    class RoundedButton: UIButton {
    
        override func layoutSubviews() {
            super.layoutSubviews()
    
            let radius = min(bounds.width, bounds.height) / 2
            layer.cornerRadius = radius
        }
    
    }
    

    And then just use this class instead of UIButton. That yields:

    enter image description here