Adding clouded shadow to UIView in swift4 - ios

I want to add shadow(it is not like default it somehow clouded and blurred) for my UIView like below
I have written an extension as
func addShadow(color: UIColor = UIColor.black, opacity: Float = 0.9, radius: CGFloat = 1, scale: Bool = true) {
self.layer.masksToBounds = false
self.layer.shadowColor = color.cgColor
self.layer.shadowOpacity = opacity
self.layer.shadowRadius = radius
self.layer.shadowPath = UIBezierPath(rect: self.bounds).cgPath
self.layer.shouldRasterize = true
self.layer.rasterizationScale = scale ? UIScreen.main.scale : 1
}
Output:
but not able to get the exact output.
Your help will be thankful.

I believe that you also need to set clipsToBounds.
self.clipsToBounds = false

I use IBInspectable to treat all the views in my app. Try it out
extension UIView {
#IBInspectable var cornerRadius: CGFloat {
set {
layer.cornerRadius = newValue
}
get {
return layer.cornerRadius
}
}
#IBInspectable var borderWidth: CGFloat {
set {
layer.borderWidth = newValue
}
get {
return layer.borderWidth
}
}
#IBInspectable var borderColor: UIColor? {
set {
layer.borderColor = newValue?.cgColor
}
get {
return UIColor(cgColor: layer.borderColor!)
}
}
#IBInspectable var shadowOffset: CGSize {
set {
layer.shadowOffset = newValue
}
get {
return layer.shadowOffset
}
}
#IBInspectable var shadowOpacity: Float {
set {
layer.shadowOpacity = newValue
}
get {
return layer.shadowOpacity
}
}
#IBInspectable var shadowRadius: CGFloat {
set {
layer.shadowRadius = newValue
}
get {
return layer.shadowRadius
}
}
#IBInspectable var shadowColor: UIColor? {
set {
layer.shadowColor = newValue?.cgColor
}
get {
return UIColor(cgColor: layer.shadowColor!)
}
}
}
in your case you should fix shadowOffset property.

You should disable clipToBounds in your 'containerView' (view that has your shadow dropping view placed as a subview)
Take a look at an example:
import UIKit
extension UIView {
func addShadow(color: UIColor = UIColor.black, opacity: Float = 0.9, radius: CGFloat = 1, scale: Bool = true) {
self.layer.masksToBounds = false
self.layer.shadowColor = color.cgColor
self.layer.shadowOpacity = opacity
self.layer.shadowRadius = radius
self.layer.shadowPath = UIBezierPath(rect: self.bounds).cgPath
self.layer.shouldRasterize = true
self.layer.rasterizationScale = scale ? UIScreen.main.scale : 1
}
}
let shadowedView = UIView(frame: CGRect(x: 50, y: 50, width: 200, height: 100))
shadowedView.backgroundColor = .blue
shadowedView.layer.cornerRadius = 15.0
shadowedView.addShadow()
let mainView = UIView(frame: CGRect(x: 0, y: 0, width: 300, height:200))
mainView.backgroundColor = .white
mainView.addSubview(shadowedView)
here I will add a view container and enable clipToBounds :
let shadowedView = UIView(frame: CGRect(x: 0, y: 0, width: 200, height: 100))
shadowedView.backgroundColor = .blue
shadowedView.layer.cornerRadius = 15.0
shadowedView.addShadow()
let containerView = UIView(frame: CGRect(x: 50, y: 50, width: 200, height: 100))
containerView.addSubview(shadowedView)
containerView.clipsToBounds = true
let mainView = UIView(frame: CGRect(x: 0, y: 0, width: 300, height: 200))
mainView.backgroundColor = .white
mainView.addSubview(containerView)

Related

Label shadow not working in swift

I tried to give a shadow to label text but it does not shown.
My code
private func drawValueLabel() {
valueLabel.layer.shadowColor = UIColor.red.cgColor
valueLabel.layer.shadowOffset = CGSize.init(width: 15.0, height: 15.0)
valueLabel.layer.shadowRadius = 3.0
valueLabel.layer.shadowOpacity = 1
valueLabel.layer.masksToBounds = false
valueLabel.clipsToBounds = false
valueLabel.layer.shouldRasterize = true
valueLabel.drawText(in: self.bounds)
}
Help me to show shadow
Thanks
I'm using this UIView extension for add shadow. With this extension you can add shadow from storyboard.
extension UIView {
#IBInspectable var shadow: Bool {
get {
return layer.shadowOpacity > 0.0
}
set {
if newValue == true {
self.addShadow()
}
}
}
func addShadow(shadowColor: CGColor = UIColor.black.cgColor,
shadowOffset: CGSize = CGSize(width: 1.0, height: 2.0),
shadowOpacity: Float = 0.4,
shadowRadius: CGFloat = 3.0) {
layer.shadowColor = shadowColor
layer.shadowOffset = shadowOffset
layer.shadowOpacity = shadowOpacity
layer.shadowRadius = shadowRadius
}
}
Your code is working fine for me. Try giving some smaller offset so that you would be able to see it like
label.layer.shadowOffset = CGSize.init(width: 3.0, height: 3.0)
Use this -
label.layer.shadowColor = UIColor.black.cgColor
label.layer.shadowOpacity = 0.5
label.layer.shadowRadius = 2.0
label.layer.shadowOffset = CGSize(width: 2.0, height: 2.0)

No shadow under uiview

Hi I am trying to get a shadow under a UITextField. I have made the followin extension to UIView. But if cuts off half of the ui for TextField.
How do you add shadow underneath a UIView/UITextField?
public extension UIView {
func installShadow() {
self.layer.masksToBounds = false
self.layer.backgroundColor = UIColor.white.cgColor
self.layer.shadowColor = UIColor.lightGray.cgColor
self.layer.shadowRadius = 5
self.layer.shadowOpacity = 1
self.layer.shadowOffset = CGSize(width: 0, height: 1)
let shadowPath = CGPath(ellipseIn: CGRect(x: self.frame.origin.x,
y: self.frame.origin.y,
width: self.frame.size.width,
height: self.frame.size.height),
transform: nil)
self.layer.shadowPath = shadowPath
}
}
You have 2 issues mainly, 1. Using Frame instead of Bounds, and 2. Using CGPath(ellipseIn: your path will be an ellipse
Use this code
public extension UIView {
func installShadow() {
self.layer.masksToBounds = false
self.layer.backgroundColor = UIColor.white.cgColor
self.layer.shadowColor = UIColor.lightGray.cgColor
self.layer.shadowRadius = 5
self.layer.shadowOpacity = 1
self.layer.shadowOffset = CGSize(width: 0, height: 1)
self.layer.shadowPath = UIBezierPath(rect: self.bounds).cgPath
}
}
Hope this helps you
Try these ...
public extension UIView {
func installShadow() {
let shadowSize : CGFloat = 0.5
layer.clipsToBounds = true
let shadowPath = UIBezierPath(rect: CGRect(x: -shadowSize / 2,
y: -shadowSize / 2,
width: subView!.frame.size.width + shadowSize,
height: subView!.frame.size.height + shadowSize))
self.layer.masksToBounds = false
self.layer.shadowColor = UIColor.darkGray.cgColor
self.layer.shadowOffset = CGSize(width: 0, height: 0)
self.layer.shadowOpacity = 0.2
self.layer.shadowRadius = 5.0
self.layer.cornerRadius = 5.0
self.layer.shadowPath = shadowPath.cgPath
}
}

UITextField shadow won't show

In my xib file, I have created a generic function through which I wanted to add a bottom border through implementing a shadow to those textfields
func setupTextField(textField: UITextField) {
textField.leftViewMode = UITextFieldViewMode.always
let imageView = UIImageView();
let image = UIImage(named: "calendar");
imageView.image = image;
imageView.frame = CGRect(x: 5, y: 8, width: 20, height: 20)
textField.addSubview(imageView)
let paddingView = UIView(frame: CGRect(x: 0, y: 0, width: 40, height: textField.frame.height))
textField.leftView = paddingView
textField.borderStyle = .none
textField.layer.backgroundColor = UIColor.white.cgColor
textField.layer.masksToBounds = false
textField.layer.shadowColor = UIColor(hex: "#D8D8D8").cgColor
textField.layer.shadowOffset = CGSize(width: 0.0, height: 1.0)
textField.layer.shadowOpacity = 1.0
textField.layer.shadowRadius = 0.0
}
And I have called this function from my awakeFromNib() method and as a result it added the shadow on my 2nd UITextField but not at the 1st one. Though from debug I can see that if there is no 2nd UITextField then this would draw a shadow on my 1st one.
How to overcome this problem?
For swift 4, swift 4.2, swift 5 Please refer below answer
Can give shadow to any UIView sub classes(imageview, label, textfield, textview etc)
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.4 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 (1, 2). 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
}
}
}
Textfield shadow
swift 4.2
textFieldDOB.backgroundColor = UIColor.white textFieldDOB.clipsToBounds = false
textFieldDOB.layer.shadowColor = UIColor.black.cgColor
textFieldDOB.layer.shadowOffset = CGSize.zero
textFieldDOB.layer.shadowOpacity = 0.3
textFieldDOB.layer.shadowRadius = 6
textFieldDOB.borderStyle = .none

UIButton bottom shadow

I have a UIButton which is very similar to the standard iOS keyboard alphabet button.
I am not sure how to create a shadow only for the bottom layer like how iOS have done.
I use the below code, but I see a shadow on all the side, not just the bottom:
CALayer *buttonLayer = [[CALayer alloc] init];
buttonLayer.shadowColor = [UIColor grayColor].CGColor;
buttonLayer.shadowOffset = CGSizeMake(0.f,1.f);
buttonLayer.masksToBounds = NO;
buttonLayer.shadowOpacity = 1.f;
How can I achieve the same effect?
You can mix the cornerRadius and shadow properties. I tested it on iOS 8.
Objective-C:
[self.globeButton setImage:[UIImage imageNamed:#"Globe"] forState:UIControlStateNormal];
self.globeButton.backgroundColor = [UIColor colorWithRed:171 green:178 blue:186 alpha:1.0f];
// Shadow and Radius
self.globeButton.layer.shadowColor = [[UIColor colorWithRed:0 green:0 blue:0 alpha:0.25f] CGColor];
self.globeButton.layer.shadowOffset = CGSizeMake(0, 2.0f);
self.globeButton.layer.shadowOpacity = 1.0f;
self.globeButton.layer.shadowRadius = 0.0f;
self.globeButton.layer.masksToBounds = NO;
self.globeButton.layer.cornerRadius = 4.0f;
Swift:
globeButton.setImage(UIImage(named: "Globe"), for: .normal)
globeButton.backgroundColor = UIColor(red: 171/255, green: 178/255, blue: 186/255, alpha: 1.0)
// Shadow Color and Radius
globeButton.layer.shadowColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.25).cgColor
globeButton.layer.shadowOffset = CGSize(width: 0.0, height: 2.0)
globeButton.layer.shadowOpacity = 1.0
globeButton.layer.shadowRadius = 0.0
globeButton.layer.masksToBounds = false
globeButton.layer.cornerRadius = 4.0
Result:
SWIFT 3
import UIKit
class ButtonWithShadow: UIButton {
override func draw(_ rect: CGRect) {
updateLayerProperties()
}
func updateLayerProperties() {
self.layer.shadowColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.25).cgColor
self.layer.shadowOffset = CGSize(width: 0, height: 3)
self.layer.shadowOpacity = 1.0
self.layer.shadowRadius = 10.0
self.layer.masksToBounds = false
}
}
!! Only if you do not need corner radius and shadow simultaneously. Otherwise watch this.
Be sure to also set shadowRadius to 0:
Given a UIButton property named button set its backing layer properties like this:
self.button.layer.shadowColor = [UIColor grayColor].CGColor;
self.button.layer.shadowOffset = CGSizeMake(0, 1.0);
self.button.layer.shadowOpacity = 1.0;
self.button.layer.shadowRadius = 0.0;
I have created IBInspectable extension that will help you.
You can directly assign from storyboard
Swift 5
//MARK:- IBInspectable
extension UIView {
#IBInspectable var cornerRadius: CGFloat {
get {
return layer.cornerRadius
}
set {
layer.cornerRadius = newValue
layer.masksToBounds = newValue > 0
}
}
#IBInspectable var borderWidth: CGFloat {
get {
return layer.borderWidth
}
set {
layer.borderWidth = newValue
}
}
#IBInspectable var borderColor: UIColor? {
get {
return UIColor(cgColor: layer.borderColor!)
}
set {
layer.borderColor = newValue?.cgColor
}
}
#IBInspectable
var shadowRadius: CGFloat {
get {
return layer.shadowRadius
}
set {
layer.masksToBounds = false
layer.shadowRadius = newValue
}
}
#IBInspectable
var shadowOpacity: Float {
get {
return layer.shadowOpacity
}
set {
layer.masksToBounds = false
layer.shadowOpacity = newValue
}
}
#IBInspectable
var shadowOffset: CGSize {
get {
return layer.shadowOffset
}
set {
layer.masksToBounds = false
layer.shadowOffset = newValue
}
}
#IBInspectable
var shadowColor: UIColor? {
get {
if let color = layer.shadowColor {
return UIColor(cgColor: color)
}
return nil
}
set {
if let color = newValue {
layer.shadowColor = color.cgColor
} else {
layer.shadowColor = nil
}
}
}
}
You can try with this code:
(sorry, i only know swift, not obj c. this code will add bottom shadow on your button.
button.layer.masksToBounds = false
button.layer.shadowColor = UIColor(rgb: 0x000000, alpha: 1.0).CGColor
button.layer.shadowOpacity = 1.0
button.layer.shadowRadius = 0
button.layer.shadowOffset = CGSizeMake(0, 1.0)
View bottom shadow
swift 4.2
viewTop.layer.shadowOffset = CGSize(width: 0, height: 1)
viewTop.layer.shadowColor = UIColor.lightGray.cgColor
viewTop.layer.shadowOpacity = 1
viewTop.layer.shadowRadius = 5
viewTop.layer.masksToBounds = false
in swift 2.0 add shadow uiview (uibutton) with code before class declaration or in swift file functions:
extension UIView {
func addShadowView(width:CGFloat=0.2, height:CGFloat=0.2, Opacidade:Float=0.7, maskToBounds:Bool=false, radius:CGFloat=0.5){
self.layer.shadowColor = UIColor.blackColor().CGColor
self.layer.shadowOffset = CGSize(width: width, height: height)
self.layer.shadowRadius = radius
self.layer.shadowOpacity = Opacidade
self.layer.masksToBounds = maskToBounds
}
}
in viewdidload add this code
button.addShadowView()
CornerRadius and shadow don't mix well on the same layer. So you will have to embed your "to be cornered" UIButton inside an UIView. The shadow will be applied on this UIView.
The following code, given as an example, produces the image below it:
import UIKit
class CustomButton: UIButton {
required init(coder decoder: NSCoder) {
super.init(coder: decoder)
backgroundColor = UIColor.whiteColor()
}
override func drawRect(rect: CGRect) {
updateLayerProperties()
}
func updateLayerProperties() {
layer.masksToBounds = true
layer.cornerRadius = 12.0
//superview is your optional embedding UIView
if let superview = superview {
superview.backgroundColor = UIColor.clearColor()
superview.layer.shadowColor = UIColor.darkGrayColor().CGColor
superview.layer.shadowPath = UIBezierPath(roundedRect: bounds, cornerRadius: 12.0).CGPath
superview.layer.shadowOffset = CGSize(width: 2.0, height: 2.0)
superview.layer.shadowOpacity = 1.0
superview.layer.shadowRadius = 2
superview.layer.masksToBounds = true
superview.clipsToBounds = false
}
}
}
Put this method into your UIView extension and play with offset value
func drawShadow(shadowColor: UIColor = UIColor.black, opacity: Float =
0.3, offset: CGSize, radius: CGFloat = 5, shouldRasterize : Bool = false) {
self.layer.shadowColor = shadowColor.cgColor
self.layer.shadowOpacity = opacity
self.layer.shadowOffset = offset
self.layer.shadowRadius = radius
self.layer.shouldRasterize = shouldRasterize
}
To add shadow to a button with corner radius:
final class CustomButton: UIButton {
private var shadowLayer: CAShapeLayer!
override func layoutSubviews() {
super.layoutSubviews()
if shadowLayer == nil {
shadowLayer = CAShapeLayer()
shadowLayer.path = UIBezierPath(roundedRect: bounds, cornerRadius: 33).cgPath
if self.backgroundColor != nil {
shadowLayer.fillColor = self.backgroundColor?.cgColor
}
else{
shadowLayer.fillColor = UIColor.white.cgColor
}
shadowLayer.shadowColor = UIColor.gray.cgColor
shadowLayer.shadowPath = shadowLayer.path
shadowLayer.shadowOffset = CGSize(width: 0.0, height: 3.0)
shadowLayer.shadowOpacity = 0.4
shadowLayer.shadowRadius = 2
layer.insertSublayer(shadowLayer, at: 0)
}
}
}
You can try with this code:
LoveButtonOutlet.layer.backgroundColor = UIColor.white.cgColor
LoveButtonOutlet.layer.cornerRadius = 10
LoveButtonOutlet.layer.borderWidth = 2
LoveButtonOutlet.layer.borderColor = UIColor.black.cgColor
LoveButtonOutlet.layer.shadowOffset = CGSize(width: 0, height: 1)
LoveButtonOutlet.layer.shadowColor = UIColor.darkGray.cgColor
LoveButtonOutlet.layer.shadowOpacity = 1
LoveButtonOutlet.layer.shadowRadius = 5
LoveButtonOutlet.layer.masksToBounds = false
extension UIButton
{
func setButtonCornerRadiusOnly(getValue:CGFloat)
{
self.layer.cornerRadius = getValue
self.clipsToBounds = true
}
func setButtonBorderColorAndHeight(getHeight:CGFloat,getColor:UIColor)
{
self.layer.borderColor = getColor.cgColor
self.layer.borderWidth = getHeight
}
func setBtnWithShadow()
{
self.layer.shadowOffset = CGSize(width: 0.5, height: 0.4)
self.layer.shadowOpacity = 0.5
self.layer.shadowRadius = 1.5
self.layer.cornerRadius = self.frame.size.height/2
self.layer.masksToBounds = false
}
}

Swift - Problems with corner radius and drop shadow

I'm trying to create a button with rounded corners and a drop shadow. No matter how I switch up, the button will not display correctly. I've tried masksToBounds = false and masksToBounds = true, but either the corner radius works and the shadow does not or the shadow works and the corner radius doesn't clip the corners of the button.
import UIKit
import QuartzCore
#IBDesignable
class Button : UIButton
{
#IBInspectable var masksToBounds: Bool = false {didSet{updateLayerProperties()}}
#IBInspectable var cornerRadius : CGFloat = 0 {didSet{updateLayerProperties()}}
#IBInspectable var borderWidth : CGFloat = 0 {didSet{updateLayerProperties()}}
#IBInspectable var borderColor : UIColor = UIColor.clearColor() {didSet{updateLayerProperties()}}
#IBInspectable var shadowColor : UIColor = UIColor.clearColor() {didSet{updateLayerProperties()}}
#IBInspectable var shadowOpacity: CGFloat = 0 {didSet{updateLayerProperties()}}
#IBInspectable var shadowRadius : CGFloat = 0 {didSet{updateLayerProperties()}}
#IBInspectable var shadowOffset : CGSize = CGSizeMake(0, 0) {didSet{updateLayerProperties()}}
override func drawRect(rect: CGRect)
{
updateLayerProperties()
}
func updateLayerProperties()
{
self.layer.masksToBounds = masksToBounds
self.layer.cornerRadius = cornerRadius
self.layer.borderWidth = borderWidth
self.layer.borderColor = borderColor.CGColor
self.layer.shadowColor = shadowColor.CGColor
self.layer.shadowOpacity = CFloat(shadowOpacity)
self.layer.shadowRadius = shadowRadius
self.layer.shadowOffset = shadowOffset
}
}
The following Swift 5 / iOS 12 code shows how to set a subclass of UIButton that allows to create instances with rounded corners and shadow around it:
import UIKit
final class CustomButton: UIButton {
private var shadowLayer: CAShapeLayer!
override func layoutSubviews() {
super.layoutSubviews()
if shadowLayer == nil {
shadowLayer = CAShapeLayer()
shadowLayer.path = UIBezierPath(roundedRect: bounds, cornerRadius: 12).cgPath
shadowLayer.fillColor = UIColor.white.cgColor
shadowLayer.shadowColor = UIColor.darkGray.cgColor
shadowLayer.shadowPath = shadowLayer.path
shadowLayer.shadowOffset = CGSize(width: 2.0, height: 2.0)
shadowLayer.shadowOpacity = 0.8
shadowLayer.shadowRadius = 2
layer.insertSublayer(shadowLayer, at: 0)
//layer.insertSublayer(shadowLayer, below: nil) // also works
}
}
}
According to your needs, you may add a UIButton in your Storyboard and set its class to CustomButton or you may create an instance of CustomButton programmatically. The following UIViewController implementation shows how to create and use a CustomButton instance programmatically:
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let button = CustomButton(type: .system)
button.setTitle("Button", for: .normal)
view.addSubview(button)
button.translatesAutoresizingMaskIntoConstraints = false
let horizontalConstraint = button.centerXAnchor.constraint(equalTo: view.centerXAnchor)
let verticalConstraint = button.centerYAnchor.constraint(equalTo: view.centerYAnchor)
let widthConstraint = button.widthAnchor.constraint(equalToConstant: 100)
let heightConstraint = button.heightAnchor.constraint(equalToConstant: 100)
NSLayoutConstraint.activate([horizontalConstraint, verticalConstraint, widthConstraint, heightConstraint])
}
}
The previous code produces the image below in the iPhone simulator:
My custom button with some shadow and rounded corners, I use it directly within the Storyboard with no need to touch it programmatically.
Swift 4
class RoundedButtonWithShadow: UIButton {
override func awakeFromNib() {
super.awakeFromNib()
self.layer.masksToBounds = false
self.layer.cornerRadius = self.frame.height/2
self.layer.shadowColor = UIColor.black.cgColor
self.layer.shadowPath = UIBezierPath(roundedRect: self.bounds, cornerRadius: self.layer.cornerRadius).cgPath
self.layer.shadowOffset = CGSize(width: 0.0, height: 3.0)
self.layer.shadowOpacity = 0.5
self.layer.shadowRadius = 1.0
}
}
To expand on Imanou's post, it's possible to programmatically add the shadow layer in the custom button class
#IBDesignable class CustomButton: UIButton {
var shadowAdded: Bool = false
#IBInspectable var cornerRadius: CGFloat = 0 {
didSet {
layer.cornerRadius = cornerRadius
layer.masksToBounds = cornerRadius > 0
}
}
override func drawRect(rect: CGRect) {
super.drawRect(rect)
if shadowAdded { return }
shadowAdded = true
let shadowLayer = UIView(frame: self.frame)
shadowLayer.backgroundColor = UIColor.clearColor()
shadowLayer.layer.shadowColor = UIColor.darkGrayColor().CGColor
shadowLayer.layer.shadowPath = UIBezierPath(roundedRect: bounds, cornerRadius: self.cornerRadius).CGPath
shadowLayer.layer.shadowOffset = CGSize(width: 1.0, height: 1.0)
shadowLayer.layer.shadowOpacity = 0.5
shadowLayer.layer.shadowRadius = 1
shadowLayer.layer.masksToBounds = true
shadowLayer.clipsToBounds = false
self.superview?.addSubview(shadowLayer)
self.superview?.bringSubviewToFront(self)
}
}
An alternative way to get more usable and consistent button.
Swift 2:
func getImageWithColor(color: UIColor, size: CGSize, cornerRadius:CGFloat) -> UIImage {
let rect = CGRectMake(0, 0, size.width, size.height)
UIGraphicsBeginImageContextWithOptions(size, false, 1)
UIBezierPath(
roundedRect: rect,
cornerRadius: cornerRadius
).addClip()
color.setFill()
UIRectFill(rect)
let image: UIImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
let button = UIButton(type: .Custom)
button.frame = CGRectMake(20, 20, 200, 50)
button.setTitle("My Button", forState: UIControlState.Normal)
button.setTitleColor(UIColor.blackColor(), forState: UIControlState.Normal)
self.addSubview(button)
let image = getImageWithColor(UIColor.whiteColor(), size: button.frame.size, cornerRadius: 5)
button.setBackgroundImage(image, forState: UIControlState.Normal)
button.layer.shadowRadius = 5
button.layer.shadowColor = UIColor.blackColor().CGColor
button.layer.shadowOpacity = 0.5
button.layer.shadowOffset = CGSizeMake(0, 1)
button.layer.masksToBounds = false
Swift 3:
func getImageWithColor(_ color: UIColor, size: CGSize, cornerRadius:CGFloat) -> UIImage? {
let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height)
UIGraphicsBeginImageContextWithOptions(size, false, 0)
color.setFill()
UIBezierPath(roundedRect: rect, cornerRadius: cornerRadius).addClip()
color.setFill()
UIRectFill(rect)
let image: UIImage = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
return image
}
let button = UIButton(type: .custom)
button.frame = CGRect(x:20, y:20, width:200, height:50)
button.setTitle("My Button", for: .normal)
button.setTitleColor(UIColor.black, for: .normal)
self.addSubview(button)
if let image = getImageWithColor(UIColor.white, size: button.frame.size, cornerRadius: 5) {
button.setBackgroundImage(image, for: .normal)
}
button.layer.shadowRadius = 5
button.layer.shadowColor = UIColor.black.cgColor
button.layer.shadowOpacity = 0.5
button.layer.shadowOffset = CGSize(width:0, height:1)
button.layer.masksToBounds = false
Swift 5 &
No need of "UIBezierPath"
view.layer.cornerRadius = 15
view.clipsToBounds = true
view.layer.masksToBounds = false
view.layer.shadowRadius = 7
view.layer.shadowOpacity = 0.6
view.layer.shadowOffset = CGSize(width: 0, height: 5)
view.layer.shadowColor = UIColor.red.cgColor
Refactored this to support any view. Subclass your view from this and it should have rounded corners. If you add something like a UIVisualEffectView as a subview to this view you likely need to use the same rounded corners on that UIVisualEffectView or it won't have rounded corners.
/// Inspiration: https://stackoverflow.com/a/25475536/129202
class ViewWithRoundedcornersAndShadow: UIView {
private var theShadowLayer: CAShapeLayer?
override func layoutSubviews() {
super.layoutSubviews()
if self.theShadowLayer == nil {
let rounding = CGFloat.init(22.0)
let shadowLayer = CAShapeLayer.init()
self.theShadowLayer = shadowLayer
shadowLayer.path = UIBezierPath.init(roundedRect: bounds, cornerRadius: rounding).cgPath
shadowLayer.fillColor = UIColor.clear.cgColor
shadowLayer.shadowPath = shadowLayer.path
shadowLayer.shadowColor = UIColor.black.cgColor
shadowLayer.shadowRadius = CGFloat.init(3.0)
shadowLayer.shadowOpacity = Float.init(0.2)
shadowLayer.shadowOffset = CGSize.init(width: 0.0, height: 4.0)
self.layer.insertSublayer(shadowLayer, at: 0)
}
}
}
Exact solution for 2020 syntax
import UIKit
class ColorAndShadowButton: UIButton {
override init(frame: CGRect) { super.init(frame: frame), common() }
required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder), common() }
private func common() {
// UIButton is tricky: you MUST set the clear bg in bringup; NOT in layout
backgroundColor = .clear
clipsToBounds = false
layer.insertSublayer(colorAndShadow, below: layer)
}
lazy var colorAndShadow: CAShapeLayer = {
let s = CAShapeLayer()
// set your button color HERE (NOT on storyboard)
s.fillColor = UIColor.black.cgColor
// now set your shadow color/values
s.shadowColor = UIColor.red.cgColor
s.shadowOffset = CGSize(width: 0, height: 10)
s.shadowOpacity = 1
s.shadowRadius = 10
// now add the shadow
layer.insertSublayer(s, at: 0)
return s
}()
override func layoutSubviews() {
super.layoutSubviews()
// you MUST layout these two EVERY layout cycle:
colorAndShadow.frame = bounds
colorAndShadow.path = UIBezierPath(roundedRect: bounds, cornerRadius: 12).cgPath
}
}
Note that the very old top answer here is correct but has a critical error
Note that UIButton is unfortunately quite different from UIView in iOS.
Due to a strange behavior in iOS, you must set the background color (which of course must be clear in this case) in initialization, not in layout. You could just set it clear in storyboard (but you usually click it to be some solid color simply so you can see it when working in storyboard.)
In general combos of shadows/rounding are a real pain in iOS. Similar solutions:
https://stackoverflow.com/a/57465440/294884 - image + rounded + shadows
https://stackoverflow.com/a/41553784/294884 - two-corner problem
https://stackoverflow.com/a/59092828/294884 - "shadows + hole" or "glowbox" problem
https://stackoverflow.com/a/57400842/294884 - the "border AND gap" problem
https://stackoverflow.com/a/57514286/294884 - basic "adding" beziers
To improve PiterPan's answer and show a real shadow (not just a background with no blur) with a circular button in Swift 3:
override func viewDidLoad() {
super.viewDidLoad()
myButton.layer.masksToBounds = false
myButton.layer.cornerRadius = myButton.frame.height/2
myButton.clipsToBounds = true
}
override func viewDidLayoutSubviews() {
addShadowForRoundedButton(view: self.view, button: myButton, opacity: 0.5)
}
func addShadowForRoundedButton(view: UIView, button: UIButton, opacity: Float = 1) {
let shadowView = UIView()
shadowView.backgroundColor = UIColor.black
shadowView.layer.opacity = opacity
shadowView.layer.shadowRadius = 5
shadowView.layer.shadowOpacity = 0.35
shadowView.layer.shadowOffset = CGSize(width: 0, height: 0)
shadowView.layer.cornerRadius = button.bounds.size.width / 2
shadowView.frame = CGRect(origin: CGPoint(x: button.frame.origin.x, y: button.frame.origin.y), size: CGSize(width: button.bounds.width, height: button.bounds.height))
self.view.addSubview(shadowView)
view.bringSubview(toFront: button)
}
Corner Radius with Shadow
Short and simple way !!!!!
extension CALayer {
func applyCornerRadiusShadow(
color: UIColor = .black,
alpha: Float = 0.5,
x: CGFloat = 0,
y: CGFloat = 2,
blur: CGFloat = 4,
spread: CGFloat = 0,
cornerRadiusValue: CGFloat = 0)
{
cornerRadius = cornerRadiusValue
shadowColor = color.cgColor
shadowOpacity = alpha
shadowOffset = CGSize(width: x, height: y)
shadowRadius = blur / 2.0
if spread == 0 {
shadowPath = nil
} else {
let dx = -spread
let rect = bounds.insetBy(dx: dx, dy: dx)
shadowPath = UIBezierPath(rect: rect).cgPath
}
}
Use of code
btn.layer.applyCornerRadiusShadow(color: .black,
alpha: 0.38,
x: 0, y: 3,
blur: 10,
spread: 0,
cornerRadiusValue: 24)
No need maskToBound
Please verify clipsToBounds is false.
OUTPUT
Extension to drop shadow and corner radius
extension UIView {
func dropShadow(color: UIColor, opacity: Float = 0.5, offSet: CGSize, shadowRadius: CGFloat = 1, scale: Bool = true, cornerRadius: CGFloat) {
let shadowLayer = CAShapeLayer()
shadowLayer.path = UIBezierPath(roundedRect: bounds, cornerRadius: cornerRadius).cgPath
shadowLayer.fillColor = UIColor.white.cgColor
shadowLayer.shadowColor = color.cgColor
shadowLayer.shadowPath = shadowLayer.path
shadowLayer.shadowOffset = offSet
shadowLayer.shadowOpacity = opacity
shadowLayer.shadowRadius = shadowRadius
layer.insertSublayer(shadowLayer, at: 0)
}
}
Here is the solution that will work!
extension UIView {
func applyShadowWithCornerRadius(color:UIColor, opacity:Float, radius: CGFloat, edge:AIEdge, shadowSpace:CGFloat) {
var sizeOffset:CGSize = CGSize.zero
switch edge {
case .Top:
sizeOffset = CGSize(width: 0, height: -shadowSpace)
case .Left:
sizeOffset = CGSize(width: -shadowSpace, height: 0)
case .Bottom:
sizeOffset = CGSize(width: 0, height: shadowSpace)
case .Right:
sizeOffset = CGSize(width: shadowSpace, height: 0)
case .Top_Left:
sizeOffset = CGSize(width: -shadowSpace, height: -shadowSpace)
case .Top_Right:
sizeOffset = CGSize(width: shadowSpace, height: -shadowSpace)
case .Bottom_Left:
sizeOffset = CGSize(width: -shadowSpace, height: shadowSpace)
case .Bottom_Right:
sizeOffset = CGSize(width: shadowSpace, height: shadowSpace)
case .All:
sizeOffset = CGSize(width: 0, height: 0)
case .None:
sizeOffset = CGSize.zero
}
self.layer.cornerRadius = self.frame.size.height / 2
self.layer.masksToBounds = true;
self.layer.shadowColor = color.cgColor
self.layer.shadowOpacity = opacity
self.layer.shadowOffset = sizeOffset
self.layer.shadowRadius = radius
self.layer.masksToBounds = false
self.layer.shadowPath = UIBezierPath(roundedRect:self.bounds, cornerRadius:self.layer.cornerRadius).cgPath
}
}
enum AIEdge:Int {
case
Top,
Left,
Bottom,
Right,
Top_Left,
Top_Right,
Bottom_Left,
Bottom_Right,
All,
None
}
Finally, to apply shadow with corner radius call as per below:
viewRounded.applyShadowWithCornerRadius(color: .gray, opacity: 1, radius: 15, edge: AIEdge.All, shadowSpace: 15)
Result Image
UPDATE: If you don't see the expected output then try calling the extension method from Main Thread, that will work for sure!
DispatchQueue.main.async {
viewRounded.applyShadowWithCornerRadius(color: .gray, opacity: 1, radius: 15, edge: AIEdge.All, shadowSpace: 15)
}
UIButton Extension
Many people have proposed using a custom class of UIButton which is totally fine. Just in case you want an extension, like me, here's one. Written in Swift 5.
extension UIButton {
/// Adds a shadow to the button, with a corner radius
/// - Parameters:
/// - corner: The corner radius to apply to the shadow and button
/// - color: The color of the shaodw
/// - opacity: The opacity of the shadow
/// - offset: The offset of the shadow
/// - radius: The radius of the shadow
func addShadow(corner: CGFloat = 20, color: UIColor = .black, opacity: Float = 0.3, offset: CGSize = CGSize(width: 0, height: 5), radius: CGFloat = 5) {
let shadowLayer = CAShapeLayer()
layer.cornerRadius = corner
shadowLayer.path = UIBezierPath(roundedRect: bounds, cornerRadius: corner).cgPath
shadowLayer.fillColor = UIColor.clear.cgColor
shadowLayer.shadowColor = color.cgColor
shadowLayer.shadowPath = shadowLayer.path
shadowLayer.shadowOffset = offset
shadowLayer.shadowOpacity = opacity
shadowLayer.shadowRadius = radius
layer.insertSublayer(shadowLayer, at: 0)
}
}
If somebody need add shadows to rounded buttons in Swift 3.0, here is a good method to do it.
func addShadowForRoundedButton(view: UIView, button: UIButton, shadowColor: UIColor, shadowOffset: CGSize, opacity: Float = 1) {
let shadowView = UIView()
shadowView.backgroundColor = shadowColor
shadowView.layer.opacity = opacity
shadowView.layer.cornerRadius = button.bounds.size.width / 2
shadowView.frame = CGRect(origin: CGPoint(x: button.frame.origin.x + shadowOffset.width, y: button.frame.origin.y + shadowOffset.height), size: CGSize(width: button.bouds.width, height: button.bounds.height))
self.view.addSubview(shadowView)
view.bringSubview(toFront: button)
}
Use this method in func viewDidLayoutSubviews() as bellow:
override func viewDidLayoutSubviews() {
addShadowForRoundedButton(view: self.view, button: button, shadowColor: .black, shadowOffset: CGSize(width: 2, height: 2), opacity: 0.5)
}
The effect of this method is:
You can create a protocol and conform it to you UIView, UIButton, Cell or whatever you want like that:
protocol RoundedShadowable: class {
var shadowLayer: CAShapeLayer? { get set }
var layer: CALayer { get }
var bounds: CGRect { get }
}
​
extension RoundedShadowable {
func applyShadowOnce(withCornerRadius cornerRadius: CGFloat, andFillColor fillColor: UIColor) {
if self.shadowLayer == nil {
let shadowLayer = CAShapeLayer()
shadowLayer.path = UIBezierPath(roundedRect: bounds, cornerRadius: cornerRadius).cgPath
shadowLayer.fillColor = fillColor.cgColor
shadowLayer.shadowColor = UIColor.black.cgColor
shadowLayer.shadowPath = shadowLayer.path
shadowLayer.shadowOffset = CGSize(width: 0.0, height: 2.0)
shadowLayer.shadowOpacity = 0.2
shadowLayer.shadowRadius = 3
self.layer.insertSublayer(shadowLayer, at: 0)
self.shadowLayer = shadowLayer
}
}
}
​
class RoundShadowView: UIView, RoundedShadowable {
var shadowLayer: CAShapeLayer?
private let cornerRadius: CGFloat
private let fillColor: UIColor
init(cornerRadius: CGFloat, fillColor: UIColor) {
self.cornerRadius = cornerRadius
self.fillColor = fillColor
super.init(frame: .zero)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
super.layoutSubviews()
self.applyShadowOnce(withCornerRadius: self.cornerRadius, andFillColor: self.fillColor)
}
}
​
class RoundShadowButton: UIButton, RoundedShadowable {
var shadowLayer: CAShapeLayer?
private let cornerRadius: CGFloat
private let fillColor: UIColor
init(cornerRadius: CGFloat, fillColor: UIColor) {
self.cornerRadius = cornerRadius
self.fillColor = fillColor
super.init(frame: .zero)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
super.layoutSubviews()
self.applyShadowOnce(withCornerRadius: self.cornerRadius, andFillColor: self.fillColor)
}
}

Resources