2016-08-30 2 views
0

Это будет действительно основной вопрос.Ошибка уровня круга с super.init - Swift

Я работаю через этот ответ: Animate drawing of a circle

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

Когда я пытаюсь как это я получаю сообщение об ошибке (»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, который ссылается circleLayer я неразрешенный идентификатор:

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") 
}  

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

Благодарим за помощь.

ответ

3

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

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

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

Initialize 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") 
    } 

} 
+0

Спасибо очень много! Поэтому я предполагаю использовать его в контроллере mu view, я просто объявляю его чем-то вроде var circleLayer: CircleLayer! –

+0

Почему необязательный, хотя он, очевидно, не является необязательным? – vadian

Смежные вопросы