将CAShapeLayer添加到UIButton不工作

时间:2016-11-14 17:14:46

标签: swift uibutton uibezierpath cashapelayer

我正在开发一个Swift项目,并使用CAShapeLayer创建一个圆形UIBezeir路径,围绕UIButton创建一个圆圈。问题是,如果我将此CAShapLayer作为子层添加到UI按钮,它就不起作用。但是,在UiView上添加此子图层会创建圆圈。

以下是我的代码。

let ovalPath = UIBezierPath(arcCenter: lockButton.center, radius:
        CGFloat(lockButton.frame.size.width/2), startAngle: CGFloat(startAngle), endAngle: CGFloat(sentAngel), clockwise: true)
    UIColor.grayColor().setFill()
    ovalPath.fill()

    let circleLayer = CAShapeLayer()
    circleLayer.path = ovalPath.CGPath

    view.layer.addSublayer(circleLayer)
    circleLayer.strokeColor = UIColor.blueColor().CGColor
    circleLayer.fillColor = UIColor.clearColor().CGColor
    circleLayer.lineWidth = 10.0





    let animation = CABasicAnimation(keyPath: "strokeEnd")

    // Set the animation duration appropriately
    animation.duration = 0.5

    // Animate from 0 (no circle) to 1 (full circle)
    animation.fromValue = 0
    animation.toValue = 1


    // Do a linear animation (i.e. the speed of the animation stays the same)
    animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear)

    // Set the circleLayer's strokeEnd property to 1.0 now so that it's the
    // right value when the animation ends.
    circleLayer.strokeEnd = 3.0

    // Do the actual animation
    circleLayer.addAnimation(animation, forKey: "animateCircle")

如果我们可以将CAShapeLayer添加到UIButton,有人可以建议我吗? 感谢

2 个答案:

答案 0 :(得分:2)

您的代码存在一个非常明显的问题,即您的circleLayer 没有框架。什么都出现了,这真是太棒了。您需要设置circleLayer的框架,使其具有大小,以便相对于其超级层正确定位。

答案 1 :(得分:1)

要解决此问题,您需要删除UIButton 背景色,并将其设置为默认值。