ios - 圆形 UIButton - iPad 尺寸

标签 ios swift constraints

我有自定义的 UIButton 有圆边

import UIKit

class RoundedButton: UIButton {

    override init(frame: CGRect) {

        super.init(frame: frame)

        self.layer.cornerRadius = self.bounds.width * 0.5
        self.backgroundColor = UIColor(patternImage: UIImage(named: "map.png")!)
        self.setTitleColor(UIColor.white, for: UIControlState.normal)
    }

    required init?(coder aDecoder: NSCoder) {

        super.init(coder: aDecoder)

        self.layer.cornerRadius = self.bounds.width * 0.5
        self.backgroundColor = UIColor(patternImage: UIImage(named: "map.png")!)
        self.setTitleColor(UIColor.white, for: UIControlState.normal)
    }

}

现在我在 UIViewcontroller 的 XIB 文件中使用这个“RoundedButton”(大小为 110、110),并且设置约束以保持宽高比 w.r.t UIViewcontrollers View 。

按钮在 iPhone 模拟器中看起来是圆形的,但在 iPad 模拟器中按钮不是圆形的。当我在 viewDidAppear 中设置 layer.cornerRadius 属性时,该按钮在 iPad 模拟器中是圆形的。

请看图片

enter image description here

enter image description here

我正在寻找替代解决方案,而不是在 viewDidappear 中再次重新定义层角半径。

谢谢

最佳答案

像这样覆盖方法 layoutSubviews:

override func layoutSubviews() {
    super.layoutSubviews()
    self.layer.cornerRadius = self.bounds.width * 0.5
}

您现在还可以从 init 中删除 cornerRadius 线

有关更多信息,请参阅 UIView 文档:https://developer.apple.com/documentation/uikit/uiview/1622482-layoutsubviews

关于ios - 圆形 UIButton - iPad 尺寸,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46873484/

相关文章:

ios - 快速将部分添加到 URL

iphone - TestFlight 升级是否会破坏应用程序中的核心数据方案?

ios - UITextInput 仅在 iOS 9 中返回 nil 位置

arrays - swift 是否遇到 Java 的 2gb 最大序列化大小问题?

ios - 如何从 didSelectRowAtindexPath : function 访问单元格 imageView

database - 约束数据库

ios - 错误#2044 : Unhandled IOErrorEvent:. 文本=错误#2032:流错误

cocoa - 使用 SpriteKit 高效渲染平铺 map

Android:SQLiteConstraintException:错误代码 19:约束失败

swift - UISlider handle 在不同尺寸的 iPad 上改变宽度