Set Background Gradient on Button in Swift

前端 未结 10 1159
礼貌的吻别
礼貌的吻别 2020-12-12 21:54

I have no idea how to set the background gradient on a button (without making the background gradient an image). This is so different from Android.

Here\'s a class I

10条回答
  •  时光说笑
    2020-12-12 22:20

       class ButtonGradient : UIButton {
            override func layoutSubviews() {
    
                let layer : CAGradientLayer = CAGradientLayer()
                layer.frame.size = self.frame.size
                layer.frame.origin = CGPoint(x: 0, y: 0)
    
                //   layer.cornerRadius = CGFloat(frame.width / 20)
                let color0 = UIColor(red:255/255, green:122/255, blue:0/255, alpha:1.0).cgColor
                let color1 = UIColor(red:255/255, green:176/255, blue: 0/255, alpha:1.0).cgColor
                let color2 = UIColor(red:250/255, green:98/255, blue: 44/255, alpha:1.0).cgColor
                layer.locations = [0.5, 1.0]
                layer.startPoint = CGPoint(x: 0.0, y: 0.5)
                layer.endPoint = CGPoint(x: 0.5, y: 0.5)
                layer.colors = [color2,color0,color1]
    
                self.layer.insertSublayer(layer, at: 0)
            }
        }
    

    After that directly assign "ButtonGredient" class to particular button in Storyboard.

提交回复
热议问题