【问题标题】:Applying Gradient to button doesn't reflect in swift将渐变应用于按钮不会迅速反映
【发布时间】:2019-07-30 10:38:10
【问题描述】:

我写了以下代码,不知道我做错了什么按钮没有反映渐变

我也尝试在 awakefromNib 下调用我的函数

class ButtonGradient: UIButton {

    var color1 = #colorLiteral(red: 0.3411764801, green: 0.6235294342, blue: 0.1686274558, alpha: 1)
    var color2 = #colorLiteral(red: 0.521568656, green: 0.1098039225, blue: 0.05098039284, alpha: 1)

    var gradient = CAGradientLayer()

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

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

    }


    func applyGradient() {

        gradient.frame = self.bounds
        gradient.colors = [color1,color2]
        gradient.startPoint = CGPoint.zero
        gradient.endPoint = CGPoint.init(x: 0.0, y: 0.5)
        gradient.locations = [0,1]
        self.layer.addSublayer(gradient)


    }
}

我想将渐变垂直应用到我的按钮。

【问题讨论】:

    标签: ios swift xcode uibutton


    【解决方案1】:

    很简单,给你

        @IBDesignable class GradientButton: UIButton {
    
        @IBInspectable var topColor: UIColor = .white
        @IBInspectable var bottomColor: UIColor = .black
    
        override class var layerClass: AnyClass {
            return CAGradientLayer.self
        }
    
        override func layoutSubviews() {
            (layer as? CAGradientLayer)?.colors = [topColor.cgColor, bottomColor.cgColor]
        }
    
    }
    

    只需将类从 UIButton 更改为 GradientButton

    【讨论】:

    • 我在自定义类 func applyGradient(colors : [Any]) { gradient.frame = self.bounds gradient.colors = colors gradient.startPoint = CGPoint.zero gradient.endPoint = CGPoint. init(x: 0.0, y: 0.9) gradient.locations = [0,1] self.layer.addSublayer(gradient) self.layer.cornerRadius = self.frame.height / 2 self.clipsToBounds = true }
    猜你喜欢
    • 2018-05-07
    • 2015-05-31
    • 1970-01-01
    • 2020-11-05
    • 1970-01-01
    • 2021-05-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多