2016-11-14 54 views
0

我正在使用Swift项目,并围绕UIButton创建一个圆,使用CAShapeLayer并创建一个循环的UIBezeir路径。问题是如果我将这个CAShapLayer作为子层添加到UIbutton,它会不行。但是,在UiView上添加此子图层将创建该圆。添加CAShapeLayer到UIButton不工作

以下是我的代码。

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? 谢谢

+0

您应该可以将CAShapeLayer添加到** any ** CALayer的子图层。使其表现完全是另一个问题。你想做什么? “圆形按钮”不需要任何新图层。掩盖边界也是我没有看到的。因此,请详细说明什么是和不在工作,也许我可以帮忙。 – dfd

+0

我正在努力在按钮周围添加循环进度 –

+0

任何具体原因? –

回答

1

你的代码的一个非常明显的问题是,你的circleLayer没有框架。这真是太神奇了,任何事情都出现了。您需要设置circleLayer的框架,使其具有大小,并使其相对于其超层正确放置。

+0

它也可能帮助您查看将圆形图层放入按钮并正常工作的代码:https://github.com/mattneub/Programming-iOS-Book-Examples/blob/master/bk2ch12p566customThermometer/ch25p840customThermometer/MyCircularProgressButton。 swift – matt

+0

我是否需要提供框架,我问这是因为,我已经为UIBezeirPath提供了中心和半径。 –

+0

这不是关于路径,而是关于图层以及它在超级图层中的位置。 – matt