Created
November 13, 2025 09:16
-
-
Save dterekhov/f1e02007ac04b7937da1d817c94501bb to your computer and use it in GitHub Desktop.
UIView+Border: Access to the UIView’s border to mange its width, color, type #uikit #swift-api #real-project
This file contains hidden or 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
| import UIKit | |
| @IBDesignable extension UIView { | |
| @IBInspectable var borderColor: UIColor? { | |
| set { layer.borderColor = newValue?.cgColor } | |
| get { return layer.borderColor == nil ? nil : UIColor(cgColor: layer.borderColor!) } | |
| } | |
| } | |
| extension UIView { | |
| /// Align dashed border | |
| public func setupDashedBorder(color: UIColor) { | |
| if let borderedLayer = self.layer.sublayers?.last as? CAShapeLayer { | |
| borderedLayer.frame = self.bounds | |
| borderedLayer.path = UIBezierPath(roundedRect: self.bounds, | |
| cornerRadius: 3).cgPath | |
| } else { | |
| addBorderedLayer(color: color) | |
| } | |
| } | |
| private func addBorderedLayer(color: UIColor) { | |
| let borderedLayer = CAShapeLayer() | |
| borderedLayer.strokeColor = color.cgColor | |
| borderedLayer.fillColor = nil | |
| borderedLayer.lineDashPattern = [2, 2] | |
| borderedLayer.frame = self.bounds | |
| borderedLayer.path = UIBezierPath(roundedRect: self.bounds, cornerRadius: 3).cgPath | |
| self.layer.addSublayer(borderedLayer) | |
| } | |
| } | |
| extension UIView { | |
| public func addBottomBorder(color: UIColor?, width: CGFloat = 1) { | |
| let border = CALayer() | |
| border.backgroundColor = color?.cgColor | |
| border.frame = CGRect(x: 0, y: self.frame.height - width, width: self.frame.width, height: width) | |
| self.layer.addSublayer(border) | |
| } | |
| public func addTopBorder(color: UIColor?, width: CGFloat = 1) { | |
| let border = CALayer() | |
| border.backgroundColor = color?.cgColor | |
| border.frame = CGRect(x: 0, y: 0, width: self.frame.width, height: width) | |
| self.layer.addSublayer(border) | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment