Reputation: 9064
How can I add a shadow to the top of my UIView
I've tried the following but with no luck...
childView.layer.cornerRadius = 5;
childView.layer.masksToBounds = YES;
childView.layer.shadowOffset = CGSizeMake(-15, 20);
childView.layer.shadowRadius = 5;
childView.layer.shadowOpacity = 0.5;
Upvotes: 14
Views: 33169
Reputation: 612
Answer is in UIBezierPath
You can find a really interesting article there: https://www.hackingwithswift.com/articles/155/advanced-uiview-shadow-effects-using-shadowpath
layer.shadowOffset = CGSize(width: 0, height: -2)
layer.shadowRadius = 5
layer.shadowPath = UIBezierPath(rect: CGRect(x: -1,
y: -1,
width: self.bounds.width,
height: self.layer.shadowRadius)).cgPath
Upvotes: 0
Reputation: 39
1.Step: First create an outlet of uiview
2.Step:
buttonBackgroundView.layer.shadowOpacity = 0.7
buttonBackgroundView.layer.shadowOffset = CGSize(width: 3, height: 3)
buttonBackgroundView.layer.shadowRadius = 15.0
buttonBackgroundView.layer.shadowColor = UIColor.black.cgColor
Upvotes: 4
Reputation: 620
Swift 3 Extension:
This includes default values for the app I'm working on, but you can change them to match the style you want in your app.
enum VerticalLocation: String {
case bottom
case top
}
extension UIView {
func addShadow(location: VerticalLocation, color: UIColor = .black, opacity: Float = 0.5, radius: CGFloat = 5.0) {
switch location {
case .bottom:
addShadow(offset: CGSize(width: 0, height: 10), color: color, opacity: opacity, radius: radius)
case .top:
addShadow(offset: CGSize(width: 0, height: -10), color: color, opacity: opacity, radius: radius)
}
}
func addShadow(offset: CGSize, color: UIColor = .black, opacity: Float = 0.5, radius: CGFloat = 5.0) {
self.layer.masksToBounds = false
self.layer.shadowColor = color.cgColor
self.layer.shadowOffset = offset
self.layer.shadowOpacity = opacity
self.layer.shadowRadius = radius
}
}
Upvotes: 28
Reputation: 1312
Set your masksToBounds = NO
. The reason you are not seeing the shadow is because it is completely hidden behind your view when the masksToBounds is YES.
If your button is rounded you can instead adjust the view's imageEdgeInset value. ie: UIEdgeInsetsMake(5, 0, 0, 10);
Upvotes: 1
Reputation: 17269
You need to set the childview's masksToBounds
property to NO
in order to make the shadow visible.
childView.layer.masksToBounds = NO;
Upvotes: 6
Reputation: 498
Try setting masksToBounds to NO. According to this link Whats the best way to add a drop shadow to my UIView making that YES will clip the layers extending past the view's bounds.
Upvotes: 0