I\'ve successfully implemented drawing a shadow around my UIView like this:
block1.layer.masksToBounds = NO;
block1.layer.shadowOffset = CGSizeM
A bit of improvement for other answers, thanks to Ashok R for swift code.
Since we were creating a triangular view in the background of the view with shadow on all sides, and a white triangle on the sides shadow is not needed.
It breaks in case of views with width comparatively larger than height.
A workaround will be to shift the path for the line where shadow is not needed a bit towards that side of view, instead of creating the triangular view Path completely.
I have created an extension for that -
extension UIView {
func addshadow(top: Bool,
left: Bool,
bottom: Bool,
right: Bool,
shadowRadius: CGFloat = 2.0) {
self.layer.masksToBounds = false
self.layer.shadowOffset = CGSize(width: 0.0, height: 0.0)
self.layer.shadowRadius = shadowRadius
self.layer.shadowOpacity = 1.0
let path = UIBezierPath()
var x: CGFloat = 0
var y: CGFloat = 0
var viewWidth = self.frame.width
var viewHeight = self.frame.height
// here x, y, viewWidth, and viewHeight can be changed in
// order to play around with the shadow paths.
if (!top) {
y+=(shadowRadius+1)
}
if (!bottom) {
viewHeight-=(shadowRadius+1)
}
if (!left) {
x+=(shadowRadius+1)
}
if (!right) {
viewWidth-=(shadowRadius+1)
}
// selecting top most point
path.move(to: CGPoint(x: x, y: y))
// Move to the Bottom Left Corner, this will cover left edges
/*
|☐
*/
path.addLine(to: CGPoint(x: x, y: viewHeight))
// Move to the Bottom Right Corner, this will cover bottom edge
/*
☐
-
*/
path.addLine(to: CGPoint(x: viewWidth, y: viewHeight))
// Move to the Top Right Corner, this will cover right edge
/*
☐|
*/
path.addLine(to: CGPoint(x: viewWidth, y: y))
// Move back to the initial point, this will cover the top edge
/*
_
☐
*/
path.close()
self.layer.shadowPath = path.cgPath
}
and set the boolean true for whichever side you want the shadow to appear
myView.addshadow(top: false, left: true, bottom: true, right: true, shadowRadius: 2.0)
// shadow radius is optional above and is set as default at 2.0
or
myView.addshadow(top: true, left: true, bottom: true, right: true, shadowRadius: 2.0)
or
myView.addshadow(top: false, left: false, bottom: true, right: true, shadowRadius: 2.0)