【问题标题】:UIButtons are not correctly shaped on all devicesUIButton 在所有设备上的形状都不正确
【发布时间】:2017-10-31 09:21:47
【问题描述】:

我有一个带有四个方形按钮的 UIView 控制器,我用边框将它们设置为圆形。它在 iPhone 8 和 iPhone X 上完美运行,但在 iPhone SE 和 iPhone 8 Plus 中,UIButtons 不再是圆形的。我已将 UIButtons 设置为方形,并通过 Auto-Layout 保持该比例,但它似乎不起作用。

在我的 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 都可以

自动布局约束:

【问题讨论】:

  • 这段代码是在什么func中执行的?
  • @Flexicoder 在func viewDidLoad()
  • 尝试将代码移动到func viewDidAppear()
  • @JulienW。作为下面发布的答案,您的视图当时尚未添加到视图层次结构中,因此不知道框架的正确宽度

标签: swift xcode swift3 uibutton autolayout


【解决方案1】:

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

【讨论】:

  • viewDidLayoutSubviews 每次更新、旋转或更改控制器的视图时都会调用。
  • 或也滚动。
  • 澄清一下,真正需要覆盖的是viewDidLayoutSubviews(),而不是代码sn-p中所说的viewWillLayoutSubviews()。应该编辑答案以反映这一点。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-03-19
  • 1970-01-01
  • 1970-01-01
  • 2023-02-03
  • 2015-07-16
相关资源
最近更新 更多