-3

I am using https://github.com/keygx/GradientCircularProgress this cocoa pod to create Gradient Circle in my App

Here is my Code.

import GradientCircularProgress

class MyViewController : UIViewController {

    let progress = GradientCircularProgress()
    var progressView: UIView?

    var Opt2Btn : UIButton?

    override func viewDidLoad() 
    {
        super.viewDidLoad()

        //My Code

        self.create()

    }

    func reset()
    {
        self.progressView?.removeFromSuperview()
        //self.progressView = nil

        // Some more Code

        self.create()
    }
    func create()
    {

        let ratio: CGFloat = CGFloat(correctCount) / CGFloat(temp.count)
        let rect = CGRect(x: 0, y: 0, width: 200, height: 200)
        progressView = progress.showAtRatio(frame: rect, display: true, style: GreenLightStyle() as StyleProperty)
        progressView?.center = CGPoint(x: self.view.frame.width / 2, y: self.view.frame.width / 2 )
        view.addSubview(progressView!)
        progress.updateRatio(ratio)

        Opt2Btn = UIButton(frame: CGRect(x: 10, y: (progressView?.frame.size.height)! + 190 + (correctLbl?.frame.size.height)! , width: self.view.frame.width - 20 , height: 40))
        Opt2Btn?.setTitle("Reset", for: .normal)
        Opt2Btn?.backgroundColor = UIColor.blue
        Opt2Btn?.layer.borderColor =  UIColor .blue.cgColor
        Opt2Btn?.addTarget(self, action: #selector(self.reset), for: .touchUpInside)
        self.view.addSubview(Opt2Btn!)


    }

}

I have tried to produce the same scenario as my App. When I run this code it shows the circle perfectly for the first time. When I hit the button(Opt2Btn) it clears the circle too but not creating again. Gives this error,

fatal error: unexpectedly found nil while unwrapping an Optional value

On view.addSubview(progressView!) this line. I have tried self.progressView = nil too but didnt work.

I am new to Swift. Can anyone suggest me what am I doing wrong here? Thank you!!

iUser
  • 1,075
  • 3
  • 20
  • 49
  • I have gone through same questions but couldn't find the right solution. I was not sure where to start searching, so posted the question here hoping that might find solution or any useful Document to understand what's the problem here. – iUser Mar 22 '17 at 21:30

1 Answers1

1

It seems that removing progessView from its superview causes progress.showAtRatio, to return nil. You then force unwrap progressView in view.addSubView(progressView!) and get an exception.

If you refer to the documentation for the framework you are using, you will see that you should use

progress.dismiss(progress: progressView!)

not removeFromSuperview.

You should always take care when force-unwrapping a variable with ! - ask yourself "Could this be nil and do I want my program to crash if it is?"

Paulw11
  • 108,386
  • 14
  • 159
  • 186