Clipping borders to subviews

I’m trying to make a contour of two UIViews but by using the border property I can’t seem to achieve what I want. I’m getting the image on the left, and I want the one on the right:

example

  • How to improve tap-ability of buttons on toolbars and navigation bars in iOS 7
  • Does GCC have a GUI?
  • Truly modal UIAlertView in iPhone?
  • Using iOS 6 theme for iOS 7 app
  • How do I implement the UITapGestureRecognizer into my application
  • Remove UITextView extra border
  • Here’s my code:

        let main = UIView()
        main.frame = CGRect(x: 50, y: 50, width: 200, height: 100)
        main.backgroundColor = UIColor.clear
        self.view.addSubview(main)
    
        let v1 = UIView()
        v1.frame = CGRect(x: 0, y: 0, width: 200, height: 50)
        v1.backgroundColor = UIColor.blue
        main.addSubview(v1)
    
        let v2 = UIView()
        v2.frame = CGRect(x: 0, y: 50, width: 150, height: 50)
        v2.backgroundColor = UIColor.red
        main.addSubview(v2)
    
        main.clipsToBounds = true
        main.layer.borderColor = UIColor.black.cgColor
        main.layer.borderWidth = 3
    

    Solutions Collect From Internet About “Clipping borders to subviews”

    You need to create custom shaped border layer like so:

    let main = UIView()
    main.frame = CGRect(x: 50, y: 50, width: 200, height: 100)
    main.backgroundColor = UIColor.clear
    self.view.addSubview(main)
    
    let v1 = UIView()
    v1.frame = CGRect(x: 0, y: 0, width: 200, height: 50)
    v1.backgroundColor = UIColor.blue
    main.addSubview(v1)
    
    let v2 = UIView()
    v2.frame = CGRect(x: 0, y: 50, width: 150, height: 50)
    v2.backgroundColor = UIColor.red
    main.addSubview(v2)
    
    
    // Custom Shape Layer    
    let maskLayer = CAShapeLayer()
    maskLayer.frame = main.bounds
    
    // Custom CGPath        
    let resultPath = CGMutablePath()
    resultPath.addPath(CGPath(rect: v1.frame, transform: nil))
    resultPath.addPath(CGPath(rect: v2.frame, transform: nil))
    maskLayer.path = resultPath
    
    // Add border
    let borderLayer = CAShapeLayer()
    borderLayer.path = maskLayer.path
    borderLayer.strokeColor = UIColor.black.cgColor
    borderLayer.lineWidth = 5
    borderLayer.frame = main.bounds
    borderLayer.zPosition = -1
    main.layer.addSublayer(borderLayer)