This question already has answers here:
Is it possible to allow didSet to be called during initialization in Swift?
(8个答案)
三年前关闭。
我正在将这个库从objc移植到Swift,我发现为什么replicator层instanceCount对动画没有任何作用。有什么想法吗?
如果您查看库,它有多个同时设置动画的层实例,但在我的代码中,一次只设置一个层的动画。
https://github.com/shu223/PulsingHalo/blob/master/PulsingHalo/PulsingHaloLayer.m
public class PulsingHaloLayer2: CAReplicatorLayer {

    var fromValueForRadius: Float = 0.0
    var fromValueForAlpha: Float = 0.45
    var keyTimeForHalfOpacity: Float = 0.2
    var animationDuration: NSTimeInterval = 3.0
    var pulseInterval: NSTimeInterval = 0.0
    var useTimingFunction: Bool = true
    let animationGroup: CAAnimationGroup = CAAnimationGroup()
    var repetitions: Float = Float.infinity
    var radius: CGFloat = 200.0 {
        didSet {
            let tempPos = position
            let diameter = radius * 2

            bounds = CGRect(x: 0.0, y: 0.0, width: diameter, height: diameter)
            cornerRadius = radius
            position = tempPos
        }
    }
    var haloLayerNumber: Int = 4 {
        didSet {
            instanceCount = 4
            instanceDelay = (animationDuration + pulseInterval) / Double(haloLayerNumber)
        }
    }

    override init() {
        super.init()
        contentsScale = UIScreen.mainScreen().scale
        opacity = 0.0
        backgroundColor = UIColor.blueColor().CGColor
        haloLayerNumber = 4

        setupAnimationGroup()
        addAnimation(animationGroup, forKey: "pulse")
    }

    required public init(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    func setupAnimationGroup() {
        animationGroup.duration = animationDuration + pulseInterval
        animationGroup.repeatCount = repetitions
        animationGroup.removedOnCompletion = false

        if useTimingFunction {
            let defaultCurve = CAMediaTimingFunction(name: kCAMediaTimingFunctionDefault)
            animationGroup.timingFunction = defaultCurve
        }

        let opacityAnimation = CAKeyframeAnimation(keyPath: "opacity")
        opacityAnimation.duration = animationDuration
        opacityAnimation.values = [fromValueForAlpha, 0.45, 0]
        opacityAnimation.keyTimes = [0, keyTimeForHalfOpacity, 1]

        let scaleAnimation = CABasicAnimation(keyPath: "transform.scale.xy")
        scaleAnimation.fromValue = fromValueForRadius
        scaleAnimation.toValue = 1
        scaleAnimation.duration = animationDuration

        animationGroup.animations = [opacityAnimation, scaleAnimation]
    }

}

最佳答案

当您调用haloLayerNumber = 4时,这不会触发didSet块,因为它发生在init内部。
您可以使用闭包来解决这个问题:({ haloLayerNumber = 4 })()。或者您可以从instanceCount内部手动更新instanceDelay/init

07-28 12:08