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

问题描述 投票:0回答:1

我写过这个自定义按钮类

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

按钮类本身有问题还是约束问题?我找不到解决方案。

swift button constraints scale shadow
1个回答
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
}
}

希望这对你有所帮助

© www.soinside.com 2019 - 2024. All rights reserved.