Set Background Gradient on Button in Swift

前端 未结 10 1244
礼貌的吻别
礼貌的吻别 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:15

    Here, I have taken one UIView and add button in it.

         @IBOutlet weak var btnCenter: UIButton!
         @IBOutlet weak var viewCenter: UIView!
    
        // Create a gradient layer
        let gradient = CAGradientLayer()
    
        // gradient colors in order which they will visually appear
        gradient.colors = [UIColor.yello.cgColor, UIColor.blue.cgColor]
    
        // Gradient from left to right
        gradient.startPoint = CGPoint(x: 0.0, y: 0.5)
        gradient.endPoint = CGPoint(x: 1.0, y: 0.5)
    
        // set the gradient layer to the same size as the view
        gradient.frame = viewCenter.bounds
    
        // add the gradient layer to the views layer for rendering
        viewCenter.layer.insertSublayer(gradient, at: 0)
    
        // Tha magic! Set the button as the views mask
        viewCenter.mask = btnCenter
    
        //Set corner Radius and border Width of button
        btnCenter.layer.cornerRadius =  btnCenter.frame.size.height / 2
        btnCenter.layer.borderWidth = 5.0
    

提交回复
热议问题