I am trying to set the custom border color of UIView programmatically in Swift.
We can create method for it. Simply use it.
public func createBorderForView(color: UIColor, radius: CGFloat, width: CGFloat = 0.7) {
self.layer.borderWidth = width
self.layer.cornerRadius = radius
self.layer.shouldRasterize = false
self.layer.rasterizationScale = 2
self.clipsToBounds = true
self.layer.masksToBounds = true
let cgColor: CGColor = color.cgColor
self.layer.borderColor = cgColor
}
Write the code in your viewDidLoad()
self.view.layer.borderColor = anyColor().CGColor
And you can set Color
with RGB
func anyColor() -> UIColor {
return UIColor(red: 0.0/255.0, green: 0.0/255.0, blue: 0.0/255.0, alpha: 1.0)
}
Learn something about CALayer
in UIKit
Swift 5.2, UIView+Extension
extension UIView {
public func addViewBorder(borderColor:CGColor,borderWith:CGFloat,borderCornerRadius:CGFloat){
self.layer.borderWidth = borderWith
self.layer.borderColor = borderColor
self.layer.cornerRadius = borderCornerRadius
}
}
You used this extension;
yourView.addViewBorder(borderColor: #colorLiteral(red: 0.6, green: 0.6, blue: 0.6, alpha: 1), borderWith: 1.0, borderCornerRadius: 20)
In Swift 4 you can set the border color and width to UIControls using below code.
let yourColor : UIColor = UIColor( red: 0.7, green: 0.3, blue:0.1, alpha: 1.0 )
yourControl.layer.masksToBounds = true
yourControl.layer.borderColor = yourColor.CGColor
yourControl.layer.borderWidth = 1.0
< Swift 4, You can set UIView's border width and border color using the below code.
yourView.layer.borderWidth = 1
yourView.layer.borderColor = UIColor.red.cgColor
If you Use Swift 2.0+
self.yourView.layer.borderWidth = 1
self.yourView.layer.borderColor = UIColor(red:222/255, green:225/255, blue:227/255, alpha: 1).cgColor
Swift 3.0
groundTrump.layer.borderColor = UIColor.red.cgColor