【问题标题】:UIButton with added Gradient cuts off添加了渐变的 UIButton 被切断
【发布时间】:2017-05-29 04:52:18
【问题描述】:

所以我通过扩展将渐变应用到 UIButton:

extension UIButton {

    func addGradient(withColors colors:[CGColor]) {
      let layer_: CAGradientLayer = CAGradientLayer()
      layer_.frame = self.bounds
      layer_.colors = colors
      layer_.shouldRasterize = true
      layer_.rasterizationScale = UIScreen.main.scale
      self.layer.insertSublayer(layer_, at: 0)
    }

}

通过以下方式将其应用于 UIButton:

@IBOutlet weak var startButton: UIButton! {
    didSet {
        startButton.backgroundColor = ECConstants.GenericColors.buttonOrange
        startButton.setTitleColor(UIColor.white, for: .normal)
        startButton.addGradient(withColors: [UIColor.white.withAlphaComponent(0.3).cgColor, UIColor.clear.cgColor])
    }
}

不幸的是,在 iPad Pro 12.9 英寸 (iOS 10.1) 上,它似乎缩短了按钮的宽度。我也尝试在 viewDidLoad 中应用它,但无济于事。

所以我的问题是如何让渐变一直穿过?或者哪里是设置渐变的最佳位置?

【问题讨论】:

  • 尝试在点击期间将按钮的宽度记录到控制台。这可以确认按钮与您期望的一样宽(看起来像问题)。

标签: ios swift ipad uibutton cagradientlayer


【解决方案1】:

为按钮添加渐变的扩展是正确的,您需要修复的是设置渐变的位置。

移动

startButton.backgroundColor = ECConstants.GenericColors.buttonOrange
startButton.setTitleColor(UIColor.white, for: .normal)
startButton.addGradient(withColors: [UIColor.white.withAlphaComponent(0.3).cgColor, UIColor.clear.cgColor])

viewDidAppearviewDidLayoutSubviews

这是因为一旦调用了viewDidAppear(),就会计算所有视图的大小。

粗糙度:(支持设备旋转)

确保在viewDidLayoutSubviews() 中重新计算子层大小。您的按钮将在设备旋转时更改大小,因此您还需要手动更改子层大小。

【讨论】:

  • 我最终将 startButton.addGradient 呼叫从 didSet 移动到 viewDidLayoutSubviews,这似乎有效。
猜你喜欢
  • 1970-01-01
  • 2020-03-16
  • 2017-05-29
  • 2019-09-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-02-04
  • 2012-03-27
相关资源
最近更新 更多