【问题标题】:GradientLayer doesn't fill UIButton bounds horizontallyGradientLayer 不会水平填充 UIButton 边界
【发布时间】:2015-08-19 19:39:51
【问题描述】:

我创建了一个带有渐变层的自定义 UIButton。当我在我的 iPhone 上测试应用程序时,按钮垂直填充了渐变层,但是渐变层只填充了水平方向的 3/4 按钮。它仍然会在按钮的未着色部分触发输入事件,所以我知道按钮的大小是正确的,但是我似乎无法弄清楚如何让 GradientLayer 完全填充按钮。

这是我的自定义 UIButton 的来源:

required init(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)

    let topColor    = UIColor(red: (40/255.0), green: (168/255.0), blue: (94/255.0), alpha: 1)
    let bottomColor = UIColor(red: 0, green: (134/255.0), blue: (55/255.0), alpha: 1)

    let gradientColors: [CGColor]  = [topColor.CGColor, bottomColor.CGColor]
    let gradientLocations: [Float] = [0.0, 1.0]

    let gradientLayer: CAGradientLayer = CAGradientLayer()

    gradientLayer.colors        = gradientColors
    gradientLayer.locations     = gradientLocations
    gradientLayer.frame         = self.bounds
    gradientLayer.cornerRadius  = 5.0

    self.layer.addSublayer(gradientLayer)
}

这是我在 iPhone 6 上运行应用程序时按钮的图像:

提前感谢您的帮助!

【问题讨论】:

    标签: ios objective-c iphone swift uibutton


    【解决方案1】:

    您是否使用自动布局?将渐变层框架设置为更大的框架后,按钮可能正在调整大小。

    您可以尝试在viewDidLayoutSubviews中重新设置图层框架。

    【讨论】:

    • 绝妙的解决方案!
    【解决方案2】:

    在 viewDidLayoutSubviews 中设置图层框架是可行的,但这里他在视图内,所以它应该进去

    func layout()
    

    (在调用 super 之后)。

    【讨论】:

      【解决方案3】:

      感谢大家的回答。帮助我走上正轨。我在 layoutSubviews() 中调整了图层的大小,这是代码

      let gradientLayer: CAGradientLayer = CAGradientLayer()
      
      required init(coder aDecoder: NSCoder) {
          super.init(coder: aDecoder)
      
          let topColor    = UIColor(red: (40/255.0), green: (168/255.0), blue: (94/255.0), alpha: 1)
          let bottomColor = UIColor(red: 0, green: (134/255.0), blue: (55/255.0), alpha: 1)
      
          let gradientColors: [CGColor]  = [topColor.CGColor, bottomColor.CGColor]
          let gradientLocations: [Float] = [0.0, 1.0]
      
          gradientLayer.colors        = gradientColors
          gradientLayer.locations     = gradientLocations
          gradientLayer.cornerRadius  = 5.0
      
          self.layer.addSublayer(gradientLayer)
      }
      
      override func layoutSubviews() {
          super.layoutSubviews();
      
          gradientLayer.frame = self.bounds
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-08-18
        • 1970-01-01
        • 1970-01-01
        • 2021-12-28
        • 1970-01-01
        • 1970-01-01
        • 2019-10-26
        • 2017-09-27
        相关资源
        最近更新 更多