swift - UIButtons 在所有设备上的形状都不正确

标签 swift xcode swift3 uibutton autolayout

我有一个带有四个方形按钮的 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 没问题

Screenshots iPhone Simulator

自动布局约束:

Auto-Layout in action

最佳答案

在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/

相关文章:

ios - UICollectionView SupplementaryView 将 UIButton 添加到页脚

ios - 编码其模型中没有嵌套属性的嵌套对象

iphone - 如何从主包的资源中获取图像路径

ios - 程序化自动布局 UI 元素

swift - 从 Core Data 取数据只返回一个值

ios - SwiftUI 因一个用户的 EXC_BREAKPOINT (SIGTRAP) 而崩溃,我无法在模拟器中复制它

ios - Storyboard选项卡栏未着色

ios - 如何在 Swift 中单击 TextField 外部时隐藏 TextField 中的 TEXT?

ios - 无法连接 IBAction 以查看

arrays - 在 swift 3 中从数组中删除特定对象