【问题标题】:Swift - Custom button class shadow size scaling not workingSwift - 自定义按钮类阴影大小缩放不起作用
【发布时间】:2019-04-10 16:48:23
【问题描述】:

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

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 上,一切都完美契合

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

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

【问题讨论】:

  • layer.shadowPath = UIBezierPath(roundedRect: bounds, cornerRadius: 5).cgPath。问题就在那里。当awakeFromNib() 被调用时,bounds 是来自 Xib 的那个。但是,在某个时间点之后,您的按钮会调整大小以适应屏幕(我猜)。所以bounds 确实改变了,但layer.shadowPath 没有改变。您可以覆盖var frame,并使用didSet{} 再次将layer.shadowPath 重置为正确的。

标签: swift button constraints scale shadow


【解决方案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
}
}

希望对你有帮助

【讨论】:

  • 它有效。我已将 shadowPath 更改为此。 layer.shadowPath = UIBezierPath(roundedRect: background.bounds, cornerRadius: 5).cgPath 使阴影像按钮一样圆润。
  • 您是否使用了您在 updateShadow 的评论中添加的行?这有什么不同(对不起,我想学习)。
  • 对 updateShadow 是的。如果没有此代码,阴影将是矩形,而不是像按钮那样圆润。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-11-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-07-18
  • 1970-01-01
  • 2018-06-12
相关资源
最近更新 更多