tezvyn:

Add shadow and rounded corners to a UIView

AI-drafted, machine-checkedSource: interviewbeginner
WHAT IT TESTS

CALayer shadow and corner properties plus the masksToBounds conflict.

OUTLINE

cornerRadius needs masksToBounds true, but that clips the shadow; set shadowPath to keep both and stay performant.

WHAT THIS TESTS This looks easy but exposes whether you understand the interaction between corner clipping and shadows, and the performance cost of letting the system compute a shadow path.

A GOOD ANSWER COVERS Rounded corners are set with view.layer.cornerRadius. To actually clip the view's content to that radius you also set layer.masksToBounds (or view.clipsToBounds) to true. Shadows live on the layer too: shadowColor, shadowOffset, shadowRadius, and shadowOpacity, which defaults to zero so nothing shows until you raise it. The conflict is that masksToBounds true clips everything to the bounds, including the shadow, so the shadow vanishes. The standard resolution is to put rounded corners and a shadow on the same layer by giving the layer an explicit shadowPath, typically a UIBezierPath rounded rect, so the shadow draws outside the clipped region. A common alternative is a container view that holds the shadow while an inner view does the clipping.

COMMON WRONG ANSWERS Setting cornerRadius and masksToBounds and then expecting a shadow to appear. Leaving shadowPath unset, which forces the render server to compute the shadow shape from the alpha channel every frame, causing an expensive off-screen pass during animation. Forgetting shadowOpacity defaults to zero.

LIKELY FOLLOW-UPS Why shadowPath matters for performance: it avoids off-screen rendering and lets the GPU rasterize a known shape. When shouldRasterize helps and its rasterizationScale pitfall. The newer maskedCorners property to round only specific corners.

ONE CONCRETE EXAMPLE For a card view you set view.layer.cornerRadius = 12 and view.clipsToBounds = true so the image content is rounded. Then on a wrapping container you set layer.shadowColor, layer.shadowOpacity = 0.2, layer.shadowOffset = CGSize(width: 0, height: 2), layer.shadowRadius = 6, and layer.shadowPath = UIBezierPath(roundedRect: bounds, cornerRadius: 12).cgPath. The inner view clips, the outer view casts a cheap, crisp shadow, and scrolling stays smooth.

Read the original → developer.apple.com

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.