shadowPath无法使用UIButton

时间:2014-07-03 11:34:08

标签: uibutton swift calayer shadow

我正在创建一个这样的按钮:

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)

之后我尝试使用我自己的shadowPath添加阴影,如下所示:

        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)

我真正的影子路径要复杂得多。

根本不显示阴影。

可能是什么问题?

2 个答案:

答案 0 :(得分:2)

问题与bezier路径有关:原点应为0,0。

更改您的代码如下:

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

答案 1 :(得分:0)

我知道这已经晚了,但对于仍然偶然发现此问题的任何人,请将您的影子代码移至扩展程序并在 viewDidLayoutSubviews 或 viewWillLayoutSubviews 中调用它,因为 shadowPath 需要计算视图的边界或框架。

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