prior swift 3 i was adding shadow in my UIView like this :
//toolbar is an UIToolbar (UIView)
toolbar.layer.masksToBounds = false
toolbar.layer.shadowOffset
Very easy to use extension for UIView, editable directly from storyboard. Swift 4+
@IBDesignable extension UIView {
@IBInspectable var shadowColor: UIColor?{
set {
guard let uiColor = newValue else { return }
layer.shadowColor = uiColor.cgColor
}
get{
guard let color = layer.shadowColor else { return nil }
return UIColor(cgColor: color)
}
}
@IBInspectable var shadowOpacity: Float{
set {
layer.shadowOpacity = newValue
}
get{
return layer.shadowOpacity
}
}
@IBInspectable var shadowOffset: CGSize{
set {
layer.shadowOffset = newValue
}
get{
return layer.shadowOffset
}
}
@IBInspectable var shadowRadius: CGFloat{
set {
layer.shadowRadius = newValue
}
get{
return layer.shadowRadius
}
}
}
loginView.layer.shadowOpacity = 1.0
I will suggest you to use below the library because it allows you to set default values in one file and you can use it everywhere in the project without making one line of change. https://github.com/Shahbaz89khan/ShadowView
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 want to use it as a IBInspectable property for your views you can add this extension
import UIKit
extension UIView {
private static var _addShadow:Bool = false
@IBInspectable var addShadow:Bool {
get {
return UIView._addShadow
}
set(newValue) {
if(newValue == true){
layer.masksToBounds = false
layer.shadowColor = UIColor.black.cgColor
layer.shadowOpacity = 0.075
layer.shadowOffset = CGSize(width: 0, height: -3)
layer.shadowRadius = 1
layer.shadowPath = UIBezierPath(rect: bounds).cgPath
layer.shouldRasterize = true
layer.rasterizationScale = UIScreen.main.scale
}
}
}
}
func applyShadowOnView(_ view:UIView) {
view.layer.cornerRadius = 8
view.layer.shadowColor = UIColor.darkGray.cgColor
view.layer.shadowOpacity = 1
view.layer.shadowOffset = CGSize.zero
view.layer.shadowRadius = 5
}