2017-01-14 3 views
0

ボタンのグラデーションカラーを作成するにはコードが必要です。作成方法はわかりません。私は層と、このコードのような公共のクラスで試してみましたが、クラスのdoesntは、私は、あなたがlayoutSubViews()self.boundsにごgradientLayer.frameを設定すべきだと思うUButtonのグラデーション

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

[スイフトのボタンの背景グラデーションを設定]の可能な複製(http://stackoverflow.com/questions/37903124/set-background-gradient-on-button-in-swift) – shallowThought

答えて

0

表示され、それは問題ないはず

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() 
    } 
} 
関連する問題