Reputation: 865
I am trying to add a drop shadow to a UIView. Here is my code for adding shadow.
func addDropShadow() {
layer.cornerRadius = 5.0
layer.masksToBounds = false
layer.shadowColor = UIColor.darkGray.cgColor
layer.shadowOpacity = 0.5
layer.shadowOffset = CGSize(width: 2, height: 2)
layer.shadowRadius = 4
layer.shadowPath = UIBezierPath(rect: bounds).cgPath
layer.shouldRasterize = true
layer.rasterizationScale = UIScreen.main.scale
}
It works fine if device is in portrait mode, but on landscape mode shadow either gets clipped off
When I rotate device back again to landscape shadow path moves out of screen.
I thought this might be due to orientation change frame of view also gets updated. So I updated shadow path property in viewDidLayoutSubviews method. But the behaviour remains the same.
Here is my code
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
self.dropShadowView.layer.shadowPath = UIBezierPath(rect: self.dropShadowView.bounds).cgPath
}
Am I doing something wrong here?.
Upvotes: 0
Views: 455
Reputation: 77486
You will find it much easier to manage the shadow if you make this a subclass of UIView
and override layoutSubviews()
:
@IBDesignable
class SimpleShadowedView: UIView {
override func layoutSubviews() {
super.layoutSubviews()
layer.cornerRadius = 5.0
layer.masksToBounds = false
layer.shadowColor = UIColor.darkGray.cgColor
layer.shadowOpacity = 0.5
layer.shadowOffset = CGSize(width: 2, height: 2)
layer.shadowRadius = 4
layer.shadowPath = UIBezierPath(rect: bounds).cgPath
layer.shouldRasterize = true
layer.rasterizationScale = UIScreen.main.scale
}
}
Note also that, by adding the @IBDesignable
designation you can also see the output during design-time.
Set the Custom Class of your view in Storyboard / Interface builder to SimpleShadowedView
:
It will show at runtime:
If you select Editor -> Refresh All Views
(or, Automatically Refresh Views
), you'll also see it at design-time.
Upvotes: 4