2017-01-14 1 views
0

버튼 배경 그라데이션 색상을 만들기 위해 몇 가지 코드가 필요합니다. 제발 어떻게 만드는지 잘 모릅니다. 나는 레이어와이 코드와 같은 공용 클래스와 시도하지만 클래스 나던 내가, 당신이 layoutSubViews()self.boundsgradientLayer.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() 
    } 
} 
관련 문제