【问题标题】:Horizontal Gradient colour Showing Half only in Swift?水平渐变颜色仅在 Swift 中显示一半?
【发布时间】:2020-05-28 04:01:48
【问题描述】:

我正在尝试为 Button Baground 提供渐变颜色,我正在尝试使用以下代码

func setGradientBackground(colorOne: UIColor, colorTwo: UIColor) {
        let gradientLayer = CAGradientLayer()
        gradientLayer.frame = bounds
        gradientLayer.colors = [colorOne.cgColor, colorTwo.cgColor]
        gradientLayer.locations = [0.0, 1.0]
        gradientLayer.startPoint = CGPoint(x: 1.0, y: 0.0)
        gradientLayer.endPoint = CGPoint(x: 0.0, y: 1.0)
        layer.insertSublayer(gradientLayer, at: 0)
    }

@IBOutlet weak var loginbtn: UIButton!
loginbtn.setGradientBackground(colorOne: UIColor.red, colorTwo: UIColor.blue)

我正在尝试访问此方法,它将显示如下输出我们如何解决此问题,

如果我添加以下代码

override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        loginbtn.setGradientBackground(colorOne: UIColor.red, colorTwo: UIColor.green)
    }

它将显示以下错误。

【问题讨论】:

标签: ios swift colors gradient


【解决方案1】:

确保您在自动布局设置按钮大小后设置渐变框架。

如果您对按钮进行子类化,您可以在layoutSubviews() 中这样做。

否则,在您的视图控制器中执行此操作的好地方是viewDidLayoutSubviews()

override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()

    loginbtn.setGradientBackground(colorOne: UIColor.red, colorTwo: UIColor.blue)
}

编辑

根据您发布的第二张图片 - 从viewDidLayoutSubviews() 调用时会出现重叠渐变...作为自动布局“发挥作用”,可以多次调用,而您是 每次调用时添加一个新层

我不知道您在自定义类中还可以做什么,但请尝试如下:

class GradButton: UIButton {

    let gradientLayer = CAGradientLayer()

    override init(frame: CGRect) {
        super.init(frame: frame)
        commonInit()
    }

    required init?(coder: NSCoder) {
        super.init(coder: coder)
        commonInit()
    }

    func commonInit() -> Void {

        gradientLayer.locations = [0.0, 1.0]

        // top-right to bottom-left
        gradientLayer.startPoint = CGPoint(x: 1.0, y: 0.0)
        gradientLayer.endPoint = CGPoint(x: 0.0, y: 1.0)

        // we only add the layer once, here when called from init    
        layer.addSublayer(gradientLayer)

    }

    func setGradientBackground(colorOne: UIColor, colorTwo: UIColor) {
        gradientLayer.colors = [colorOne.cgColor, colorTwo.cgColor]
    }

    override func layoutSubviews() {
        super.layoutSubviews()
        gradientLayer.frame = bounds
    }

}

class MyTest: UIViewController {

    @IBOutlet var loginbtn: GradButton!

    override func viewDidLoad() {
        super.viewDidLoad()
        loginbtn.setGradientBackground(colorOne: .red, colorTwo: .yellow)
    }

}

结果:

【讨论】:

  • 您的代码正在运行,但在结尾部分它显示为一个关节
猜你喜欢
  • 2016-11-18
  • 2019-08-27
  • 1970-01-01
  • 2017-04-30
  • 1970-01-01
  • 2012-02-07
  • 1970-01-01
  • 2023-03-19
  • 1970-01-01
相关资源
最近更新 更多