How to set the custom border color of UIView programmatically?
Solution 1:
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
Solution 2:
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
Solution 3:
Use @IBDesignable and @IBInspectable to do the same.
They are re-useable, easily modifiable from the Interface Builder and the changes are reflected immediately in the Storyboard
Conform the objects in the storyboard to the particular class
Code Snippet:
@IBDesignable
class CustomView: UIView{
@IBInspectable var borderWidth: CGFloat = 0.0{
didSet{
self.layer.borderWidth = borderWidth
}
}
@IBInspectable var borderColor: UIColor = UIColor.clear {
didSet {
self.layer.borderColor = borderColor.cgColor
}
}
override func prepareForInterfaceBuilder() {
super.prepareForInterfaceBuilder()
}
}
Allows easy modification from Interface Builder:
Solution 4:
You can write an extension to use it with all the UIViews eg. UIButton, UILabel, UIImageView etc. You can customise my following method as per your requirement, but I think it will work well for you.
extension UIView{
func setBorder(radius:CGFloat, color:UIColor = UIColor.clearColor()) -> UIView{
var roundView:UIView = self
roundView.layer.cornerRadius = CGFloat(radius)
roundView.layer.borderWidth = 1
roundView.layer.borderColor = color.CGColor
roundView.clipsToBounds = true
return roundView
}
}
Usage:
btnLogin.setBorder(7, color: UIColor.lightGrayColor())
imgViewUserPick.setBorder(10)
Solution 5:
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)