Last active
March 29, 2024 12:05
-
-
Save leilee/21166d3d548d50658b583c15d94f87a1 to your computer and use it in GitHub Desktop.
Add gradient border to UIView
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} | |
} |
Hi fukemy
Sure
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
is this method work for label text too?