2016-11-09 56 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()的內部執行此操作。但是,您必須記住您在故事板中按鈕上設置的約束條件。

相關問題