Search code examples
swiftxcodeswift3uibuttonautolayout

UIButtons are not correctly shaped on all devices


I've an UIView Controller with four square buttons and I've set them round with a border. It works perfectly on iPhone 8 and iPhone X but in iPhone SE and iPhone 8 Plus the UIButtons are not round anymore. I've set the UIButtons to be square and to keep that ratio with Auto-Layout but it doesn't appear to work.

In my ViewController.Swift, I've linked the four UIButtons and then I've applied the same code as below :

@IBOutlet weak var topLeftButtonImage: UIButton!


// Edit it to round
topLeftButtonImage.layer.cornerRadius = topLeftButtonImage.frame.size.width/2
topLeftButtonImage.clipsToBounds = true

// Add border
topLeftButtonImage.layer.borderColor = UIColor.white.cgColor // Button border color
topLeftButtonImage.layer.borderWidth = 4 // Button border width

Here you can see the behaviour on iPhone SE and iPhone 8 Plus. iPhone 8 and iPhone X are fine.

Screenshots iPhone Simulator

Auto-Layout constraints :

Auto-Layout in action


Solution

  • set button cornerRadius in viewDidLayoutSubviews method of viewcontroller

     override func viewWillLayoutSubviews() {
        super.viewWillLayoutSubviews()
        // Edit it to round
        topLeftButtonImage.layer.cornerRadius = topLeftButtonImage.bounds.size.height / 2
        topLeftButtonImage.clipsToBounds = true
    
        // Add border
        topLeftButtonImage.layer.borderColor = UIColor.white.cgColor // Button border color
        topLeftButtonImage.layer.borderWidth = 4 // Button border width
    }