-1

I'm trying to make an IOS Unit Converter app using swift. But I'm getting an exception when a textfield is empty after entering some value.

I've already tried to solve the problem with 'if let' and 'guard statement' but could not get it to work maybe I did something wrong somewhere.


class ViewController: UIViewController, UITextFieldDelegate {

    @IBOutlet weak var textOunce: UITextField!
    @IBOutlet weak var textPound: UITextField!
    @IBOutlet weak var textGram: UITextField!
    @IBOutlet weak var textStone: UITextField!
    @IBOutlet weak var textStonePound: UITextField!
    @IBOutlet weak var textKg: UITextField!

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        textOunce.delegate = self
        textPound.delegate = self
        textGram.delegate = self
        textStone.delegate = self
        textStonePound.delegate = self
        textKg.delegate = self

        textOunce.addTarget(self, action: #selector(self.textFieldDidChange(_:)), for: .editingChanged)
        textPound.addTarget(self, action: #selector(self.textFieldDidChange(_:)), for: .editingChanged)
        textGram.addTarget(self, action: #selector(self.textFieldDidChange(_:)), for: .editingChanged)
        textStone.addTarget(self, action: #selector(self.textFieldDidChange(_:)), for: .editingChanged)
        textStonePound.addTarget(self, action: #selector(self.textFieldDidChange(_:)), for: .editingChanged)
        textKg.addTarget(self, action: #selector(self.textFieldDidChange(_:)), for: .editingChanged)
    }

    @objc func textFieldDidChange(_ textField: UITextField) {

        var toOunce = Double(textOunce.text!)!
        toOunce = toOunce / 16
        textPound.text = "\(toOunce)"

    }

}

I want to dynamically fill the other textfields when the user enters a value on a textfield and set the value to zero instead of throwing a nil exception if the user decides to erase all the values they entered in a textfield.

Tom Fitzburgh
  • 41
  • 1
  • 8

1 Answers1

0

You need to check whether inputed data is in double format or can it be converted to Double if yes, then if part will be executed otherwise it will goes inside else part.

Replace textFieldDidChange method with below -

 @objc func textFieldDidChange(_ textField: UITextField) {

    if var toOunce = Double(textField.text!) {

        toOunce = toOunce / 16
        textPound.text = "\(toOunce)"

    }else{

        debugPrint("Invalid input")
    }

 }

To add 0 if user didn't enter anything or added spaces -

func textFieldShouldReturn(_ textField: UITextField) -> Bool {

    if textField.text?.trimmingCharacters(in: .whitespaces).count  == 0{

      textField.text = "0"
    }

    textField.resignFirstResponder() // This line is important to add text to it. 
    return false // OR true  // Have to pass any value because it needs Bool return.
}
Amir Khan
  • 1,313
  • 1
  • 13
  • 37