2017-09-06 12 views
0

でリサイズUIButtonの背景を追加します。ただし私は勾配でUIButtonに背景を追加することができ、このコードでグラデーションカラー

public func addBackgroundAndGradient(to: UIView, gradient1: CGColor, gradient2: CGColor, cornerRadius: CGFloat = 5){ 
    let backgroundImage = UIImageView() 
    backgroundImage.frame.size = to.frame.size 
    backgroundImage.clipsToBounds = true 
    backgroundImage.layer.borderColor = UIColor.white.cgColor 
    backgroundImage.layer.borderWidth = 0.5 
    to.insertSubview(backgroundImage, at: 0) 

    let gradient = CAGradientLayer() 
     let gradient1 = UIColor(red: 200/255, green: 100/255, blue: 5/255, alpha: 1).cgColor 
     let gradient2 = UIColor(red: 1, green: 128/255, blue: 0, alpha: 1).cgColor 
     gradient.colors = [gradient1, gradient2, gradient2, gradient1] 

    gradient.locations = [0.0, 0.35, 0.65, 1.0] 
    gradient.frame.size = to.frame.size 
    backgroundImage.layer.addSublayer(gradient) 
    backgroundImage.layer.cornerRadius = cornerRadius 
} 

を私はUIButtonのための新しいタイトルを設定すると、背景がサイズ変更されません。テキストをイニシャルよりも長くすると、テキストはバックグラウンドを超えます。

UIButtonのグラデーションを使用して背景のサイズを変更するにはどうすればよいですか?これを行うための

答えて

0

、カスタムUIButtonのサブクラスを作成し、及びその層クラスとしてCAGradientLayerを設定する必要があります。

@IBOutlet weak var expandableGradientButton: ExpandableGradientButton! 
... 
public func addBackgroundAndGradient(to: UIView, gradient1: CGColor, gradient2: CGColor, cornerRadius: CGFloat = 5){ 
    let backgroundImage = UIImageView() 
    backgroundImage.frame.size = to.frame.size 
    backgroundImage.clipsToBounds = true 
    backgroundImage.layer.borderColor = UIColor.white.cgColor 
    backgroundImage.layer.borderWidth = 0.5 

    let gradient1 = UIColor(red: 100/255, green: 140/255, blue: 2/255, alpha: 1).cgColor 
    let gradient2 = UIColor(red: 123/255, green: 158/255, blue: 54.0/255.0, alpha: 1).cgColor 
    if let butonLayer = to.layer as? CAGradientLayer 
    { 
     butonLayer.colors = [gradient1, gradient2, gradient2, gradient1] 
     butonLayer.locations = [0.0, 0.35, 0.65, 1.0] 
     butonLayer.cornerRadius = cornerRadius 
    } 
} 

class ExpandableGradientButton: UIButton { 

override class var layerClass: AnyClass { 
    get { 
      return CAGradientLayer.self 
     } 
    } 
} 

その後、あなたはにあなたの関数を変更する必要がありますつまり、UIButtonのレイヤーとしてグラデーションレイヤーを使用する必要があり、自動的にサイズ変更されます。 注:これはUIButtonだけでなく、他のUIViewサブクラスでも使用できます。

関連する問題