【问题标题】:UIButton shadow not drawingUIButton阴影不绘制
【发布时间】:2016-10-06 01:47:09
【问题描述】:

我正在尝试创建一种方法来配置应用程序中的按钮。我的方法按预期执行,但没有绘制阴影。它不会崩溃。

我使用以下方法创建了一个UIButton extension

func configureWhiteText(withBackgroundColor buttonColor: UIColor?) {
    // basic configuration
    tintColor = UIColor.white
    setTitleColor(UIColor.white, for: .normal)
    backgroundColor = buttonColor

    // layer stuff
    layer.drawsAsynchronously = true
    layer.shouldRasterize = true
    layer.cornerRadius = 10.0
    layer.masksToBounds = false
    layer.shadowColor = UIColor.black.cgColor
    layer.shadowOffset = CGSize(width: 5.0, height: 5.0)
    layer.shadowRadius = 5.0
}

我已经在viewDidLoad 中的UITableViewController 和'viewWillAppear` 中尝试过,但没有运气:

myButton.configureWhiteText(withBackgroundColor: UIColor.blue)

按钮位于UITableViewController 的分组静态单元格中。除了面向阴影的代码行之外,一切都在配置方法中工作。 layer.cornerRadius 按预期绕过拐角,但其他面向layer 的线都没有画阴影。

我已验证layer.masksToBounds = false。我还尝试注释掉layer.drawsAsynchronouslylayer.shouldRasterize 无济于事。

感谢任何进一步的想法/建议。

【问题讨论】:

  • 就像下面的答案一样,您只需添加一行代码即可。您可以参考此link 了解更多信息。

标签: ios swift uibutton swift3


【解决方案1】:

您忽略了实际打开阴影的设置 - shadowOpacity。添加这一行:

layer.shadowOpacity = 0.5

Badda bing badda boom.

【讨论】:

【解决方案2】:

你需要设置阴影路径,假设它在一个uibutton扩展中

self.layer.shadowPath = UIBezierPath(roundedRect: self.bounds, cornerRadius: 20).CGPath

【讨论】:

  • 感谢您的建议。我添加了该行并得到相同的结果。
【解决方案3】:

对于像我这样的人,即使 layer.shadowOpacity 设置为非零值,他们仍可能面临同样的问题。如果您的按钮背景颜色是 UIColor.clear,您应该将其更改为其他颜色,例如白色。

【讨论】:

    猜你喜欢
    • 2010-11-16
    • 2012-02-16
    • 1970-01-01
    • 2015-01-20
    • 1970-01-01
    • 1970-01-01
    • 2016-06-14
    • 1970-01-01
    • 2016-11-14
    相关资源
    最近更新 更多