How to set the custom border color of UIView programmatically?

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

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

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

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

    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

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

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

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

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

    Swift 3.0

           groundTrump.layer.borderColor = UIColor.red.cgColor
    
    0 讨论(0)
提交回复
热议问题