2017-01-14 3 views
0

Bitte ich brauche einige Code, um eine Schaltfläche Hintergrund Gradiente Farbe, bitte ich weiß nicht, wie man es macht. Ich habe mit Schichten versucht und einer öffentlichen Klasse wie dieser Code, aber die tut KlasseGradient für UIButton

public class GradientButton: UIButton { 

override public func layoutSubviews() { 
    super.layoutSubviews() 
    layoutGradientButtonLayer() 
} 

// MARK: Private 
private func layoutGradientButtonLayer() { 
    let gradientLayer = CAGradientLayer() 
    let color1 = UIColor(red:0.05, green:0.29, blue:0.49, alpha: 1.0).cgColor as CGColor 
    let color2 = UIColor(red:0.08, green:0.23, blue:0.39, alpha: 1.0).cgColor as CGColor 
    gradientLayer.colors = [color1, color2] 
    gradientLayer.locations = [0.0, 1.0] 
    self.layer.addSublayer(gradientLayer) 
} 

}

+0

Mögliches Duplikat von [Hintergrundfarbe auf Schaltfläche in Swift festlegen] (http://stackoverflow.com/questions/37903124/set-background-gradient-on-button-in-swift) – shallowThought

Antwort

0

erscheinen ich glaube, Sie Ihre gradientLayer.frame-self.bounds in layoutSubViews() setzen sollte, und es sollte in Ordnung sein

0
extension UIView { 
    func applyGradient(colours: [UIColor]) -> Void { 
     self.applyGradient(colours, locations: nil) 
    } 

    func applyGradient(colours: [UIColor], locations: [NSNumber]?) -> Void { 
     let gradient: CAGradientLayer = CAGradientLayer() 
     gradient.frame = self.bounds 
     gradient.colors = colours.map { $0.CGColor } 
     gradient.locations = locations 
     self.layer.insertSublayer(gradient, atIndex: 0) 
    } 
} 

class ViewController: UIViewController { 

    @IBOutlet weak var btn: UIButton! 

    override func viewDidLoad() { 
     super.viewDidLoad() 

     self.btn.titleLabel?.textColor = UIColor.whiteColor() 

     self.btn.applyGradient([UIColor.yellowColor(), UIColor.blueColor()]) 
     self.view.applyGradient([UIColor.yellowColor(), UIColor.blueColor(), UIColor.redColor()], locations: [0.0, 0.5, 1.0]) 
    } 

    override func didReceiveMemoryWarning() { 
     super.didReceiveMemoryWarning() 
    } 
}