2016-11-09 9 views
2

ボタンのバッチにグラデーションレイヤーを追加するためのUIButtonサブクラスを作成しました。ボタンの高さを設定する方法があるかどうか疑問に思っていますすべて同じ高さになるでしょう。これは、それが可能だと場合、私は思ったんだけどそう勾配層のための私のコードですコードで、私はそれを配置する必要があります:ボタンの高さを設定するUIButtonサブクラスXcode/Swift

public class GradientButton: UIButton { 

override public func layoutSubviews() { 
    super.layoutSubviews() 
    createGradientBackground() 

} 
func createGradientBackground() { 

    let gradientLayer = CAGradientLayer() 
    gradientLayer.frame = self.layer.bounds 

    let color1 = UIColor(red:0.05, green:0.29, blue:0.49, alpha:1.0).CGColor as CGColorRef 
    let color2 = UIColor(red:0.08, green:0.23, blue:0.39, alpha:1.0).CGColor as CGColorRef 

    gradientLayer.colors = [color1, color2] 

    gradientLayer.locations = [0.0, 1.0] 

    self.layer.insertSublayer(gradientLayer, atIndex: 0) 
    } 
} 

答えて

2

は確かに、ちょうど追加:

init() { 
    self.frame.size.height = 50.0 
    //Do other stuff you may want 
} 

OR:

func createGradientBackground() { 

    let gradientLayer = CAGradientLayer() 
    gradientLayer.frame = self.layer.bounds 

    let color1 = UIColor(red:0.05, green:0.29, blue:0.49, alpha:1.0).CGColor as CGColorRef 
    let color2 = UIColor(red:0.08, green:0.23, blue:0.39, alpha:1.0).CGColor as CGColorRef 

    gradientLayer.colors = [color1, color2] 

    gradientLayer.locations = [0.0, 1.0] 

    self.layer.insertSublayer(gradientLayer, atIndex: 0) 

    //set custom height wanted 
    self.frame.size.height = 50.0 
} 

これは、カスタムinit()またはcreateGradientBackground()内で実行できます。しかし、ストーリーボードのボタンにどのような制約が設定されているかを覚えておく必要があります。