Skip to content

Instantly share code, notes, and snippets.

@4brunu
Last active January 11, 2017 14:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save 4brunu/990d3d4ffb9eab2b9ead1b4df8e2ddc6 to your computer and use it in GitHub Desktop.
Save 4brunu/990d3d4ffb9eab2b9ead1b4df8e2ddc6 to your computer and use it in GitHub Desktop.
Button with gradient and round courners doesn't show text
import UIKit
extension UIButton {
func applyBackgroundGradientStyle() {
roundCorners()
applyGradient()
self.setTitleColor(UIColor.white, for: .normal)
}
private func roundCorners() {
self.layer.cornerRadius = self.frame.size.height/2
self.clipsToBounds = true
}
private func applyGradient() {
let gradientLayer = CAGradientLayer()
gradientLayer.frame = self.bounds
let startColor = UIColor.red.cgColor as CGColor
let endColor = UIColor.blue.cgColor as CGColor
gradientLayer.colors = [startColor, endColor]
gradientLayer.startPoint = CGPoint(x: 0.0, y: 0.5)
gradientLayer.endPoint = CGPoint(x: 1, y: 0.5)
gradientLayer.locations = [0.0, 1.0]
self.layer.insertSublayer(gradientLayer, at: 0)
}
//If I comment this function, the title will apear, but the gradient doesn't have the correct frame
override open func layoutSubviews() {
super.layoutSubviews()
if let subLayers = self.layer.sublayers {
for layer in subLayers {
if layer is CAGradientLayer {
layer.frame = self.bounds
}
}
}
}
}
let button = UIButton(frame: CGRect(x: 0, y: 0, width: 100, height: 20))
button.setTitle("Button", for: .normal)
button.applyBackgroundGradientStyle()
button.frame = CGRect(x: 0, y: 0, width: 200, height: 40)
button
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment