Search code examples
uibuttonswiftcalayershadow

shadowPath is not working with UIButton


I am creating a button like this:

let authorizationButton = UIButton()
    let authorizationButtonHeight = 50.0
    let authorizationButtonX = 10.0
    let authorizationButtonWidth = UIScreen.mainScreen().bounds.size.width - authorizationButtonX * 2
    let authorizationButtonY = UIScreen.mainScreen().bounds.size.height - 10.0 - authorizationButtonHeight

    authorizationButton.frame = CGRectMake(authorizationButtonX, authorizationButtonY, authorizationButtonWidth, authorizationButtonHeight)

After that I am trying to add a shadow with my own shadowPath like this:

        authorizationButton.layer.shadowPath = UIBezierPath(rect:CGRectMake(authorizationButton.frame.origin.x, authorizationButton.frame.origin.y,
        authorizationButton.frame.size.width, authorizationButton.frame.size.height)).CGPath

    authorizationButton.layer.shadowColor = UIColor.blackColor().CGColor
    authorizationButton.layer.shadowOpacity = 1.0
    authorizationButton.layer.shadowRadius = 3.0
    authorizationButton.layer.shadowOffset = CGSizeMake(3.0, 3.0)

My real shadow path is much more complicated.

Shadow is not displayed at all.

What can be the problem?


Solution

  • The problem is related to the bezier path: the origin should be 0,0.

    Change your code as follow:

    authorizationButton.layer.shadowPath = UIBezierPath(rect:
        CGRectMake(0, 
                   0, 
                   authorizationButton.frame.size.width,
                   authorizationButton.frame.size.height)).CGPath