48

Anyone know? I found a few answers, but there were too complex and going too deep. I need a simple answer.

demongolem
  • 9,474
  • 36
  • 90
  • 105
Ondrej Rafaj
  • 4,342
  • 8
  • 42
  • 65

3 Answers3

149

If the masksToBounds property is set to YES, any sublayers of the layer that extend outside its boundaries will be clipped to those boundaries. Think of the layer, in that case, as a window onto its sublayers; anything outside the edges of the window will not be visible. When masksToBounds is NO, no clipping occurs, and any sublayers that extend outside the layer's boundaries will be visible in their entirety (as long as they don't go outside the edges of any superlayer that does have masking enabled).

Noah Witherspoon
  • 57,021
  • 16
  • 130
  • 131
8

Input Design in storyboard

enter image description here

@IBOutlet weak var purpleView: UIView!  // view inside super view
@IBOutlet weak var yellowView: UIView!  // super view

override func viewDidLoad() {
    super.viewDidLoad()

    yellowView.layer.cornerRadius = 20
    yellowView.layer.masksToBounds = true
    
    // Do any additional setup after loading the view.
}

enter image description here

output after maskToBounds = true. Super view clip the subview's part which are outside the superview.

Jaykant
  • 349
  • 4
  • 11
0

iOS UIView.clipsToBounds CALayer.masksToBounds

[CALayer]

[CALayer.mask]

masksToBounds = applies mask which is equals boundaries + cornerRadius

clipsToBounds and masksToBounds are equivalent

masksToBounds by default is false that is why all sublayers are able to go out of boundaries[About]. When it is true all sublayers are clipped(corner radius is taken into account). Please note that sublayers are

  • subview's layers
  • sublayers of current layer
  • shadows

Example:

masksToBounds == false:

masksToBounds == true:

bounds vs frame: rotate 45 degrees

To debug from Xcode v11.4

Debug View Hierarchy 
 - show layers: Editor -> Show Layers
 - show as it was: Editor -> Show Clipped Content
yoAlex5
  • 29,217
  • 8
  • 193
  • 205