简体   繁体   中英

Geting a fatal “error: unexpectedly found nil while unwrapping an Optional value” when chaging value of label on button press

I keep getting nil value when I press button.

import UIKit

class ViewController: UIViewController {
 //MARK: Properties

 @IBOutlet weak var txt_vrednost: UITextField!
 @IBOutlet weak var btn_dodaj: UIButton!
 @IBOutlet weak var lbl_stanje: UILabel!
 var novcanik = 0.0

 //MARK: Acttion

 @IBAction func btn_dodaj_pressed(_ sender: Any) {

     let values = Double(txt_vrednost.text!)
     novcanik = novcanik + values!
     lbl_stanje.text=String(novcanik)

 }

 override func viewDidLoad() {
     super.viewDidLoad()

     // Do any additional setup after loading the view, typically from a nib.
  }
}

First of all make sure all your outlets are connected with storyboard. You are using force unwrap everywhere, which is causing crash :

import UIKit

class ViewController: UIViewController {

//MARK: Properties

 @IBOutlet weak var txt_vrednost: UITextField!
 @IBOutlet weak var btn_dodaj: UIButton!
 @IBOutlet weak var lbl_stanje: UILabel!

 var novcanik = 0.0

//MARK: Action

 @IBAction func btn_dodaj_pressed(_ sender: Any) {
  guard let values = txt_vrednost.text as? Double else {
      print("not convertible")
      return 
  }
 novcanik = novcanik + values
 lbl_stanje.text = "\(novcanik)"
}

override func viewDidLoad() {
 super.viewDidLoad()

 // Do any additional setup after loading the view, typically from a nib.

}
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM