constraintsswift4subviewsuperview

manual constraints not being cuasin unwrapping issue (swift4)


My code below is causing a run time error. This works If I code a lazy var as a scrollview. But this does not work if I am just trying to add a object to the view or superview. I have connected nothing from the storyboard and do not want to.

   var FIRE: UIImageView!
override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
    playSound()





       view.addSubview(FIRE)

    FIRE.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
    FIRE.topAnchor.constraint(equalTo: view.topAnchor, constant: 20).isActive = true
    FIRE.widthAnchor.constraint(equalToConstant: 400).isActive = true
    FIRE.heightAnchor.constraint(equalToConstant: 80).isActive = true
    }

Solution

  • Change

    var FIRE: UIImageView!
    

    To

    let FIRE = UIImageView()