prior swift 3 i was adding shadow in my UIView like this :
//toolbar is an UIToolbar (UIView) toolbar.layer.masksToBounds = false toolbar.layer.shadowOffset = CGSize(width: -1, height: 1) toolbar.layer.shadowRadius = 1 toolbar.layer.shadowOpacity = 0.5
but the above code is not working in swift 3 , instead of shadow my whole View's color is turned to ugly gray
anyone knows how can we add shadow in swift 3 ?
Add subview with the same color which will be centered on the parent and will be with several pixels smaller. Like this you will have space from each side of the parent. On the parent turn on clipping subviews and add shadow to the inner view. Like this, you can have an inner shadow.
CODE SNIPPET:
extension UIView { // OUTPUT 1 func dropShadow(scale: Bool = true) { layer.masksToBounds = false layer.shadowColor = UIColor.black.cgColor layer.shadowOpacity = 0.5 layer.shadowOffset = CGSize(width: -1, height: 1) layer.shadowRadius = 1 layer.shadowPath = UIBezierPath(rect: bounds).cgPath layer.shouldRasterize = true layer.rasterizationScale = scale ? UIScreen.main.scale : 1 } // OUTPUT 2 func dropShadow(color: UIColor, opacity: Float = 0.5, offSet: CGSize, radius: CGFloat = 1, scale: Bool = true) { layer.masksToBounds = false layer.shadowColor = color.cgColor layer.shadowOpacity = opacity layer.shadowOffset = offSet layer.shadowRadius = radius layer.shadowPath = UIBezierPath(rect: self.bounds).cgPath layer.shouldRasterize = true layer.rasterizationScale = scale ? UIScreen.main.scale : 1 } }
NOTE: If you don't pass any parameter to that function, then the scale argument will be true by default. You can define a default value for any parameter in a function by assigning a value to the parameter after that parameter’s type. If a default value is defined, you can omit that parameter when calling the function.
OUTPUT 1:
shadowView.dropShadow()
OUTPUT 2:
shadowView.dropShadow(color: .red, opacity: 1, offSet: CGSize(width: -1, height: 1), radius: 3, scale: true)
layer.shouldRasterize = true
will make the shadow static and cause a shadow for the initial state of theUIView
. So I would recommend not to uselayer.shouldRasterize = true
in dynamic layouts like view inside aUITableViewCell
.
Shadow using UIView Extension Swift 4
I would like to add one more line with selected answer! When we rasterizing the layer, It needs to be set to 2.0 for retina displays. Otherwise label text or images on that view will be blurry. So we need to add rasterizationScale
also.
extension UIView { func dropShadow() { layer.masksToBounds = false layer.shadowColor = UIColor.black.cgColor layer.shadowOpacity = 0.5 layer.shadowOffset = CGSize(width: -1, height: 1) layer.shadowRadius = 1 layer.shadowPath = UIBezierPath(rect: self.bounds).cgPath layer.shouldRasterize = true layer.rasterizationScale = UIScreen.main.scale } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With