UIButtons are not correctly shaped on all devices

2020-05-06 09:52发布

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

1条回答
smile是对你的礼貌
2楼-- · 2020-05-06 10:36

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
}
查看更多
登录 后发表回答