Basically, I would like to have 3 texfields labelled as follows, with a calculate button below to return values into whichever fields the user wants to know.
Frequency ...
Wavelength ...
Time Period ...
"Calculate"
- if the user enters a value in the frequency field, the wavelength = 343 / frequency and the time period = 1/frequency
- if they enter the wavelength instead, the frequency = 343 / wavelength and the time period = wavelength / 343
- if they enter the time period, the frequency = 1/time period and the wavelength = time period * 343
With the help of the comment above (Claude31), I have managed to get two of the text boxes working properly with the following code, just need to add the 3rd text box for time period...
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var frequencyField: UITextField!
@IBOutlet weak var waveLengthField: UITextField!
@IBOutlet weak var timePeriodField: UITextField!
var freq = Float(0);
var length = Float(0);
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func Calculate(_ sender: UIButton) {
freq = Float(frequencyField.text!) ?? 0.0
length = Float(waveLengthField.text!) ?? 0.0
print(freq) // Just to see when they are 0
print(length)
let speed = Float(343.0)
if freq > 0 { // Avoid a zero div in some cases
let resultWave = Float(speed / freq)
waveLengthField.text! = String(resultWave)
print(resultWave)
} else {
let resultWave = length
waveLengthField.text! = String(resultWave)
}
if length > 0 { // Avoid a zero div in some cases
let resultFreq = Float(speed / length)
frequencyField.text! = String(resultFreq)
} else {
let freqPrint = freq
frequencyField.text! = String(freqPrint)
}
}
}