我有一个带有四个方形按钮的 UIView Controller ,我将它们设置为带有边框的圆形。它在 iPhone 8 和 iPhone X 上完美运行,但在 iPhone SE 和 iPhone 8 Plus 上,UIButtons 不再是圆形的。我已将 UIButtons 设置为正方形并通过自动布局保持该比例,但它似乎不起作用。
在我的 ViewController.Swift 中,我链接了四个 UIButton,然后我应用了如下相同的代码:
@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 没问题。
自动布局约束:
最佳答案
在viewcontroller的viewDidLayoutSubviews方法中设置按钮的cornerRadius
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
}
关于swift - UIButtons 在所有设备上的形状都不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54171749/