I am trying to set the custom border color of UIView programmatically in Swift.
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:
swift 3.0
self.uiTextView.layer.borderWidth = 0.5
self.txtItemShortDes.layer.borderColor = UIColor(red:205.0/255.0, green:205.0/255.0, blue:205.0/255.0, alpha: 1.0).cgColor
swift 3
func borderColor(){
self.viewMenuItems.layer.cornerRadius = 13
self.viewMenuItems.layer.borderWidth = 1
self.viewMenuItems.layer.borderColor = UIColor.white.cgColor
}
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)