Search code examples
iosuikit

Superview border is cutting into subview


I'd like this subview to extend past its superview, but the superview's border is cutting into the subview. Is there a way to prevent this?

Example

class TheView : UIView {

    let theSubView = UIButton()


    override init(frame: CGRect) {
        super.init(frame: frame)

        layer.borderColor = UIColor.gray.cgColor
        layer.borderWidth = 1
        clipsToBounds = false

        addSubview(theSubView)

        theSubView.backgroundColor = UIColor.green
        theSubView.frame = CGRect(x: 0, y: -10, width: 50, height: 50)
    }   
}

Solution

  • Instead of using the view's layer's border, draw the border yourself:

    class TheView : UIView {
    
        let theSubView = UIButton()
    
        override func draw(_ rect: CGRect) {
            UIColor.gray.set()
            UIBezierPath(rect: rect).stroke()
        }
    
        override init(frame: CGRect) {
            super.init(frame: frame)
            clipsToBounds = false
            isOpaque = false
    
            addSubview(theSubView)
    
            theSubView.backgroundColor = UIColor.green
            theSubView.frame = CGRect(x: 0, y: -10, width: 50, height: 50)
        }   
    
        required init?(coder aDecoder: NSCoder) {
            fatalError("init(coder:) has not been implemented")
        }
    }
    

    enter image description here