Ошибка кругового слоя с super.init - Swift

Это будет действительно основной вопрос.

Я работаю над этим ответом: Анимация рисования круга

Но как ни форматирую, выдает ошибку. Из ошибки я вижу, что я не инициализировал круг, и я уверен, что это просто позиционирование, но не уверен, что или как это сделать правильно или что не так с тем, как у меня есть макет.

Когда я пытаюсь сделать это, я получаю сообщение об ошибке ('self.circleLayer' не инициализируется при вызове super.init):

import UIKit

class CircleView: UIView {

    let circleLayer: CAShapeLayer!

        override init(frame: CGRect) {
            super.init(frame: frame)


            self.backgroundColor = UIColor.clearColor()

            // Use UIBezierPath as an easy way to create the CGPath for the layer.
            // The path should be the entire circle.
            let circlePath = UIBezierPath(arcCenter: CGPoint(x: frame.size.width / 2.0, y: frame.size.height / 2.0), radius: (frame.size.width - 10)/2, startAngle: 0.0, endAngle: CGFloat(M_PI * 2.0), clockwise: true)

            // Setup the CAShapeLayer with the path, colors, and line width
            circleLayer = CAShapeLayer()
            circleLayer.path = circlePath.CGPath
            circleLayer.fillColor = UIColor.clearColor().CGColor
            circleLayer.strokeColor = UIColor.redColor().CGColor
            circleLayer.lineWidth = 5.0;

            // Don't draw the circle initially
            circleLayer.strokeEnd = 0.0

            // Add the circleLayer to the view's layer's sublayers
            layer.addSublayer(circleLayer)
        }


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

}

Затем попытался переместить его после такого инициализатора, который не дает мне ошибки):

import UIKit

    class CircleView: UIView {

            override init(frame: CGRect) {
                super.init(frame: frame)

                let circleLayer: CAShapeLayer!
                self.backgroundColor = UIColor.clearColor()

                // Use UIBezierPath as an easy way to create the CGPath for the layer.
                // The path should be the entire circle.
                let circlePath = UIBezierPath(arcCenter: CGPoint(x: frame.size.width / 2.0, y: frame.size.height / 2.0), radius: (frame.size.width - 10)/2, startAngle: 0.0, endAngle: CGFloat(M_PI * 2.0), clockwise: true)

                // Setup the CAShapeLayer with the path, colors, and line width
                circleLayer = CAShapeLayer()
                circleLayer.path = circlePath.CGPath
                circleLayer.fillColor = UIColor.clearColor().CGColor
                circleLayer.strokeColor = UIColor.redColor().CGColor
                circleLayer.lineWidth = 5.0;

                // Don't draw the circle initially
                circleLayer.strokeEnd = 0.0

                // Add the circleLayer to the view's layer's sublayers
                layer.addSublayer(circleLayer)
            }


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

    }

Но затем, когда я пытаюсь поместить в свой viewcontroller.swift функцию, которая ссылается на круговой слой, я получаю неразрешенный идентификатор:

func animateCircle(duration: NSTimeInterval) {
    // We want to animate the strokeEnd property of the circleLayer
    let animation = CABasicAnimation(keyPath: "strokeEnd")

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

    // 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 = 1.0

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

Я уверен, что это просто что-то действительно простое, но я не уверен, что.

Спасибо за вашу помощь.


person Nicholas Muir    schedule 30.08.2016    source источник


Ответы (1)


Из документации

Проверка безопасности 1

Назначенный инициализатор должен убедиться, что все свойства, представленные его классом, инициализированы до того, как он делегирует инициализатору суперкласса.

Инициализируйте circleLayer в строке объявления и переместите self.backgroundColor = ... после super.init

class CircleView: UIView {
  
  let circleLayer = CAShapeLayer()
  
  override init(frame: CGRect) {
    
    // Use UIBezierPath as an easy way to create the CGPath for the layer.
    // The path should be the entire circle.
    let circlePath = UIBezierPath(arcCenter: CGPoint(x: frame.size.width / 2.0, y: frame.size.height / 2.0), radius: (frame.size.width - 10)/2, startAngle: 0.0, endAngle: CGFloat(M_PI * 2.0), clockwise: true)
    
    super.init(frame: frame)
    // Setup the CAShapeLayer with the path, colors, and line width
    
    self.backgroundColor = UIColor.clearColor()
    circleLayer.path = circlePath.CGPath
    circleLayer.fillColor = UIColor.clearColor().CGColor
    circleLayer.strokeColor = UIColor.redColor().CGColor
    circleLayer.lineWidth = 5.0;
    
    // Don't draw the circle initially
    circleLayer.strokeEnd = 0.0
    
    // Add the circleLayer to the view's layer's sublayers
    layer.addSublayer(circleLayer)
  }
  
  
  required init(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
  }
  
}
person vadian    schedule 30.08.2016
comment
Большое спасибо! Итак, я предполагаю, что для использования его в контроллере представления mu я просто объявлю его чем-то вроде var CircleLayer : CircleLayer! - person Nicholas Muir; 30.08.2016
comment
Почему необязательный, хотя он явно необязательный? - person vadian; 30.08.2016