UIButton 在所有设备上的形状都不正确

Posted

技术标签:

【中文标题】UIButton 在所有设备上的形状都不正确【英文标题】:UIButtons are not correctly shaped on all devices 【发布时间】: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。作为下面发布的答案,您的视图当时尚未添加到视图层次结构中,因此不知道框架的正确宽度 【参考方案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()。应该编辑答案以反映这一点。

以上是关于UIButton 在所有设备上的形状都不正确的主要内容,如果未能解决你的问题,请参考以下文章

UIButton 上的 UIImage 模糊

Swift:UILabel 上的 UIButton

uiview上的按钮翻转动画超出框架

Nativescript - 不同设备上的应用启动图标形状

搜索中的第一个 UITableViewCell UIButton 保持不变

UIBarButtonItem 形状不正确