UIButton在所有设备上的形状都不正确 [英] UIButtons are not correctly shaped on all devices
问题描述
我有一个带有四个方形按钮的UIView控制器,并将它们设置为带有边框的圆形.它在iPhone 8和iPhone X上完美运行,但在iPhone SE和iPhone 8 Plus上,UIButton不再圆了.我已将UIButtons设置为正方形,并使用自动布局"保持该比例,但它似乎不起作用.
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.
在我的 ViewController.Swift 中,我链接了四个UIButton,然后应用了以下相同的代码:
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
在这里您可以看到iPhone SE和iPhone 8 Plus上的行为. iPhone 8和iPhone X很好.
Here you can see the behaviour on iPhone SE and iPhone 8 Plus. iPhone 8 and iPhone X are fine.
自动版式约束:
推荐答案
在viewcontroller的viewDidLayoutSubviews方法中设置按钮cornerRadius
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
}
这篇关于UIButton在所有设备上的形状都不正确的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!