How to set the custom border color of UIView programmatically?

后端 未结 10 434
情书的邮戳
情书的邮戳 2020-12-23 02:29

I am trying to set the custom border color of UIView programmatically in Swift.

相关标签:
10条回答
  • 2020-12-23 03:23

    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:

    0 讨论(0)
  • 2020-12-23 03:23

    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
    
    0 讨论(0)
  • 2020-12-23 03:31

    swift 3

    func borderColor(){
    
        self.viewMenuItems.layer.cornerRadius = 13
        self.viewMenuItems.layer.borderWidth = 1
        self.viewMenuItems.layer.borderColor = UIColor.white.cgColor
    }
    
    0 讨论(0)
  • 2020-12-23 03:32

    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)
    
    0 讨论(0)
提交回复
热议问题