致命错误:(在SuperView中添加和删除视图时)

时间:2017-03-22 21:19:25

标签: ios swift xcode fatal-error

我正在使用https://github.com/keygx/GradientCircularProgress这个可可豆荚在我的应用程序中创建渐变圆

这是我的代码。

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!)


    }

}

我试图制作与我的应用程序相同的方案。当我运行此代码时,它首次完美地显示了圆圈。当我按下按钮(Opt2Btn)时,它也清除圆圈但不再创建。给出了这个错误,

  

致命错误:在解包可选值时意外发现nil

view.addSubview(progressView!)这一行。我也试过了self.progressView = nil但是没有用。

我是Swift的新手。任何人都可以建议我在这里做错了什么? 谢谢!!

1 个答案:

答案 0 :(得分:1)

似乎从其超级视图中移除progessView导致progress.showAtRatio,返回nil。然后,您强制在progressView中展开view.addSubView(progressView!)并获得例外。

如果您参考您正在使用的框架的文档,您将看到应该使用

progress.dismiss(progress: progressView!)

不是removeFromSuperview

强制解包变量时应始终注意! - 问自己“这可能是零,我是否希望我的程序崩溃?”