I want to add a drop shadow using CALayer to a UI(Image)View. The following code works generally fine
previewImage.layer.shadowColor = [[UIColor blackColor] CGColor];
previewImage.layer.shadowOffset = CGSizeMake(1.0f, 1.0f);
previewImage.layer.shadowOpacity = 1.0f;
previewImage.layer.shadowRadius = 8.0f;
However, this only works if I create that view programmatically and add it as a subview to my main view. When that view is set up in InterfaceBuilder and defined as an IBOutlet UIImageView this does NOT work. No shadow appears. So what am I missing here?
shadowOpacity sets how transparent the shadow is, where 0 is invisible and 1 is as strong as possible. shadowOffset sets how far away from the view the shadow should be, to give a 3D offset effect.
Drop Shadows You can specify a path for this basic shadow by creating a UIBezierPath from your view bounds. You may also need to set the layer's masksToBound property to true if the shadow isn't showing up. By doing so, you're allowing the layer content to be drawn outside of the layer bounds.
Add a file named UIView.swift in your project (or just paste this in any file) :
import UIKit
@IBDesignable extension UIView {
/* The color of the shadow. Defaults to opaque black. Colors created
* from patterns are currently NOT supported. Animatable. */
@IBInspectable var shadowColor: UIColor? {
set {
layer.shadowColor = newValue!.CGColor
}
get {
if let color = layer.shadowColor {
return UIColor(CGColor:color)
}
else {
return nil
}
}
}
/* The opacity of the shadow. Defaults to 0. Specifying a value outside the
* [0,1] range will give undefined results. Animatable. */
@IBInspectable var shadowOpacity: Float {
set {
layer.shadowOpacity = newValue
}
get {
return layer.shadowOpacity
}
}
/* The shadow offset. Defaults to (0, -3). Animatable. */
@IBInspectable var shadowOffset: CGPoint {
set {
layer.shadowOffset = CGSize(width: newValue.x, height: newValue.y)
}
get {
return CGPoint(x: layer.shadowOffset.width, y:layer.shadowOffset.height)
}
}
/* The blur radius used to create the shadow. Defaults to 3. Animatable. */
@IBInspectable var shadowRadius: CGFloat {
set {
layer.shadowRadius = newValue
}
get {
return layer.shadowRadius
}
}
}
Then this will be available in Interface Builder for every view in the Utilities Panel > Attributes Inspector :
You can easily set the shadow now.
Notes:
- The shadow will only appear at runtime.
- clipsToBounds
should be false (by default it is)
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