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.

enter image description here

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;

Can you please tell me how to achieve the same effect. Thanks in advance.


Solution 1:

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:

UIButton + iOS Keyboard style

Solution 2:

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
    }

}

button without rounded corners with shadow

!! Only if you do not need corner radius and shadow simultaneously. Otherwise watch this.