Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Border Padding for a UIView

I created a standard border around my UIView like so:

 vwGroup.layer.borderColor = UIColor.yellow.cgColor
 vwGroup.layer.borderWidth = 2.0;

but I would like to have 5px of padding/margin/spacing between the UIView, and the border that surrounds it.

Right now it just draws the border immediately around it. I'd like to push it out so there is clear space between.

Any suggestions? I suspect insets are the way to go but can't figure it out.

Thank you!

like image 601
NullHypothesis Avatar asked Oct 24 '25 04:10

NullHypothesis


2 Answers

Insets isn't the way to go. You use inset for padding a view's internal content from its margins. For what you need your best option is to wrap your vwGroup inside another UIView and set the border in the wrapping view. Something like:

let wrappingView = UIView(frame: someFrame)
wrappingView.backgroundColor = .clear
wrappingView.layer.borderColor = UIColor.yellow.cgColor
wrappingView.layer.borderWidth = 2.0;
wrappingView.addSubview(vwGroup)

Of course this is just for you to get the big picture. You might want to set proper frames/constraints.

like image 155
alanpaivaa Avatar answered Oct 26 '25 18:10

alanpaivaa


swift 5.4

call like this:

customView.layer.innerBorder()

did it, by add a sublayer

extension CALayer {


    func innerBorder(borderOffset: CGFloat = 24.0, borderColor: UIColor = UIColor.blue, borderWidth: CGFloat = 2) {
        let innerBorder = CALayer()
        innerBorder.frame = CGRect(x: borderOffset, y: borderOffset, width: frame.size.width - 2 * borderOffset, height: frame.size.height - 2 * borderOffset)
        innerBorder.borderColor = borderColor.cgColor
        innerBorder.borderWidth = borderWidth
        innerBorder.name = "innerBorder"
        insertSublayer(innerBorder, at: 0)
    }
}
like image 20
dengST30 Avatar answered Oct 26 '25 18:10

dengST30