AndrewShmig
AndrewShmig

Reputation: 4923

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?

Upvotes: 1

Views: 2306

Answers (2)

Ahmed Ben Henda
Ahmed Ben Henda

Reputation: 1

I know this is late but for anyone who still stumbles upon this problem, move your shadow code to an extension and call it in viewDidLayoutSubviews or viewWillLayoutSubviews, because shadowPath require bounds or frame of the view to be calculated.

example: override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() myButton.applyShadows() }

Upvotes: 0

mxb
mxb

Reputation: 3330

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

Upvotes: 2

Related Questions