Skip to content

Instantly share code, notes, and snippets.

@KentarouKanno
Created May 29, 2016 03:03
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save KentarouKanno/46eeb79a8239585a16fd38f349417e94 to your computer and use it in GitHub Desktop.
Save KentarouKanno/46eeb79a8239585a16fd38f349417e94 to your computer and use it in GitHub Desktop.
UIButton Gradient

UIButton Gradient

★ UIButtonの背景にグラデーションを掛ける

class GradientButton: UIButton {
    
    var startColor: UIColor = UIColor.yellowColor()
    var endColor  : UIColor = UIColor.orangeColor()
    
    init(frame: CGRect, startColor: UIColor, endColor: UIColor) {
        super.init(frame: frame)
        
        self.startColor = startColor
        self.endColor   = endColor
        createGradient()
        setCornerRadius()
    }
    
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }
    
    func createGradient() {
        let gradientColors: [CGColor] = [startColor.CGColor, endColor.CGColor]
        let gradientLayer: CAGradientLayer = CAGradientLayer()
        gradientLayer.colors = gradientColors
        gradientLayer.frame = bounds
        layer.insertSublayer(gradientLayer, atIndex: 0)
    }
    
    func setCornerRadius() {
        layer.masksToBounds = true
        layer.cornerRadius  = 10
        layer.borderColor   = UIColor.redColor().CGColor
        layer.borderWidth   = 1
    }
}


// Usage 

let button = GradientButton(frame: CGRectMake(100, 100, 200, 50), startColor: UIColor.yellowColor(), endColor: UIColor.orangeColor())
button.setTitle("Title", forState: .Normal)
button.addTarget(self, action: #selector(ViewController.push), forControlEvents: .TouchUpInside)
view.addSubview(button)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment