2016-11-14 33 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