I'm working on a unit converter written in Swift that will automatically display the updated units within the appropriate NSTextField
s. For this example, if the user inputs minutes into the minutesField
, the secondsField
and hoursField
should automatically update to display the converted values from the properties. Below is an example of the code in my view controller:
import Cocoa
class ViewController: NSViewController {
@IBOutlet weak var secondsField: NSTextField!
@IBOutlet weak var minutesField: NSTextField!
@IBOutlet weak var hoursField: NSTextField!
var sec: Double = 1
var min: Double = 1
var hr: Double = 1
let conv = [[1, 0.0166666666666667, 0.000277777777777778],
[60, 1, 0.0166666666666667],
[3600, 60, 1]]
func updateTextFields() {
secondsField.stringValue = "\(sec)"
minutesField.stringValue = "\(min)"
hoursField.stringValue = "\(hr)"
}
}
extension ViewController: NSTextFieldDelegate {
override func controlTextDidChange(obj: NSNotification) {
let tag = obj.object?.tag() ?? 0
let text = obj.object?.stringValue ?? "1"
let value = Double(text) ?? 1.0
switch tag {
case 0:
// base unit = seconds
sec = value
min = value * conv[0][1]
hr = value * conv[0][2]
case 1:
// base unit = minutes
sec = value * conv[1][0]
min = value
hr = value * conv[1][2]
case 2:
// base unit = hours
sec = value * conv[2][0]
min = value * conv[2][1]
hr = value
default:
"none"
}
updateTextFields()
}
}
The code above updates the text fields but the active field with the input freezes after the first key stroke. For example, if you try to enter 60
into the seconds field, the next key stroke does not do anything. The number 6.0
appears after the first key stroke (see image below). This is likely due to the function that is called after the properties are updated. The properties are updated based on the tag of the active text field.
Is it possible to have a function that will update all the other text fields other than the currently active field?