Swift-自定义按钮类阴影大小缩放不起作用

时间:2019-04-10 16:48:24

标签: swift button constraints scale shadow

我已经编写了这个自定义按钮类

class RoundedButton: UIButton {

override func awakeFromNib() {

    layer.cornerRadius = 5

    layer.shadowColor = UIColor.black.cgColor
    layer.shadowOffset = CGSize(width: 0.0, height: 0.0)
    layer.shadowOpacity = 0.2
    layer.shadowRadius = 1.0
    layer.masksToBounds = false
    layer.shadowPath = UIBezierPath(roundedRect: bounds, cornerRadius: 5).cgPath

    layer.contents = center
    layer.shouldRasterize = true
    layer.rasterizationScale = UIScreen.main.scale
}
}

在我的iPhone X上,一切都很合适

enter image description here

但是当我使用屏幕较小的设备时,阴影无法根据按钮大小正确缩放。

enter image description here

按钮类本身是否存在问题,还是约束问题?我找不到解决方法。

1 个答案:

答案 0 :(得分:1)

您需要更新layoutSubviews上的阴影(这也应该解决您的代码旋转似乎存在的问题)。

class RoundedButton: UIButton {
    override func layoutSubviews() {
        super.layoutSubviews()
        updateShadow(on: self)
    }

func updateShadow(on background: UIView) {
    let layer = background.layer
    layer.shadowPath = UIBezierPath(rect: background.bounds).cgPath
    layer.masksToBounds = false
    layer.shadowColor = UIColor.black.cgColor
    layer.shadowOffset = CGSize(width: 0, height: 0.0)
    layer.shadowRadius = 4
    layer.shadowOpacity = 0.22
}

override func awakeFromNib() {

    layer.cornerRadius = 5
    layer.shadowColor = UIColor.black.cgColor
    layer.shadowOffset = CGSize(width: 0.0, height: 0.0)
    layer.shadowOpacity = 0.2
    layer.shadowRadius = 1.0
    layer.masksToBounds = false
    layer.shadowPath = UIBezierPath(roundedRect: bounds, cornerRadius: 5).cgPath
    layer.contents = center
    layer.shouldRasterize = true
    layer.rasterizationScale = UIScreen.main.scale
}
}

希望这对您有帮助