To add this component to your Xcode project using CocoaPods, add the following to your Podfile
:
pod 'MaterialComponents/ShadowLayer'
Then, run the following command:
pod install
Before using shadow layer, you'll need to import it:
import MaterialComponents
#import "MaterialShadowLayer.h"
Example of a custom button based on UIButton with Material Design shadows:
class ShadowButton: UIButton { override class var layerClass: AnyClass { return MDCShadowLayer.self } }
@interface ShadowButton : UIButton @end @implementation ShadowButton + (Class)layerClass { return [MDCShadowLayer class]; } @end
Add the custom button to view:
let button = ShadowButton(type: .system) button.frame = CGRect(x: 100, y: 100, width: 200, height: 50) button.setTitle("Button", for: .normal) let buttonLayer = button.layer as! MDCShadowLayer buttonLayer.elevation = ShadowElevation(6) addSubview(button)
ShadowButton *button = [ShadowButton buttonWithType:UIButtonTypeSystem]; button.frame = CGRectMake(100, 100, 200, 50); [button setTitle: @"Button" forState:UIControlStateNormal]; [(MDCShadowLayer *)button.layer setElevation:6.f]; [self addSubview:button];
Creating a custom UIView with a shadow:
class ShadowedView: UIView { override class var layerClass: AnyClass { return MDCShadowLayer.self } var shadowLayer: MDCShadowLayer { return self.layer as! MDCShadowLayer } var elevation: ShadowElevation { get { return self.shadowLayer.elevation } set { self.shadowLayer.elevation = newValue } } }
@interface ShadowedView : UIView @end @implementation ShadowedView + (Class)layerClass { return [MDCShadowLayer class]; } - (MDCShadowLayer)shadowLayer { return (MDCShadowLayer *)self.layer; } - (void)setElevation:(CGFloat)points { [(MDCShadowLayer *)self.layer setElevation:points]; } @end
To improve performance, consider rasterizing MDCShadowLayer when the view using the shadow is not animating or changing size.
layer.shouldRasterize = true layer.rasterizationScale = UIScreen.main.scale
self.layer.shouldRasterize = YES; self.layer.rasterizationScale = [UIScreen mainScreen].scale;
Disable rasterization before animating MDCShadowLayer.