Skip to content

Instantly share code, notes, and snippets.

@leilee
Last active March 29, 2024 12:05
Show Gist options
  • Save leilee/21166d3d548d50658b583c15d94f87a1 to your computer and use it in GitHub Desktop.
Save leilee/21166d3d548d50658b583c15d94f87a1 to your computer and use it in GitHub Desktop.
Add gradient border to UIView
public extension UIView {
private static let kLayerNameGradientBorder = "GradientBorderLayer"
public func setGradientBorder(
width: CGFloat,
colors: [UIColor],
startPoint: CGPoint = CGPoint(x: 0.5, y: 0),
endPoint: CGPoint = CGPoint(x: 0.5, y: 1)
) {
let existedBorder = gradientBorderLayer()
let border = existedBorder ?? CAGradientLayer()
border.frame = bounds
border.colors = colors.map { return $0.cgColor }
border.startPoint = startPoint
border.endPoint = endPoint
let mask = CAShapeLayer()
mask.path = UIBezierPath(roundedRect: bounds, cornerRadius: 0).cgPath
mask.fillColor = UIColor.clear.cgColor
mask.strokeColor = UIColor.white.cgColor
mask.lineWidth = width
border.mask = mask
let exists = existedBorder != nil
if !exists {
border.name = UIView.kLayerNameGradientBorder
layer.addSublayer(border)
}
}
public func removeGradientBorder() {
self.gradientBorderLayer()?.removeFromSuperlayer()
}
private func gradientBorderLayer() -> CAGradientLayer? {
let borderLayers = layer.sublayers?.filter { return $0.name == UIView.kLayerNameGradientBorder }
if borderLayers?.count ?? 0 > 1 {
fatalError()
}
return borderLayers?.first as? CAGradientLayer
}
}
@gintechsystems
Copy link

Removing the gradient border does not work for me using iOS 12, I added border.name = UIView.kLayerNameGradientBorder under !exists to make it work.

@deepakappsinvo1
Copy link

Hi gintechsystems

add one line below border.endPoint = endPoint and then will work fine in any iOS version
border.name = UIView.kLayerNameGradientBorder

Thanks :)

@fukemy
Copy link

fukemy commented Jan 14, 2022

is this method work for label text too?

@deepakappsinvo1
Copy link

deepakappsinvo1 commented Jan 14, 2022

Hi fukemy

Sure

@jung-yun
Copy link

jung-yun commented Mar 1, 2024

Thank you~! it works very well for me

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment