Swift how to make a shadow

Swift dev shows how to add shadows to objects with code example.

Creating a Shadow in Swift

A shadow is a visual effect that adds dimension and depth to an element. With Swift, you can create a shadow using the layer.shadow property. This allows you to set the color, opacity, offset, radius, and path of the shadow. Here is an example of how to create a shadow on a UIView:


let myView = UIView(frame: CGRect(x: 0, y: 0, width: 100, height: 100))
myView.backgroundColor = .white

let shadowLayer = CAShapeLayer()
shadowLayer.frame = myView.bounds
shadowLayer.shadowColor = UIColor.black.cgColor
shadowLayer.shadowOffset = CGSize(width: 0, height: 4)
shadowLayer.shadowOpacity = 0.5
shadowLayer.shadowRadius = 10

myView.layer.addSublayer(shadowLayer)

This code creates a UIView with a black shadow with an offset of 4 points, an opacity of 0.5, and a radius of 10 points. You can customize the shadow further by modifying the shadowColor, shadowOffset, shadowOpacity, and shadowRadius properties.

Answers (0)