Search code examples
swiftmacosnstextfield

Update Swift NSTextfield variable when it's changed


How can I write this so that it updates the variable when the user finishes using the field (for Cocoa?). The aim is to allow the user to specify a custom IP address for the TV's location on the network.

import Cocoa
import Alamofire

class ViewController: NSViewController, NSTextFieldDelegate {

@IBAction func MenuButton(_ sender: NSButtonCell) {
    triggerRemoteControl(irccc: "AAAAAQAAAAEAAABgAw==")
}
@IBAction func ReturnButton(_ sender: NSButton) {
    triggerRemoteControl(irccc: "AAAAAgAAAJcAAAAjAw==")
}

@IBOutlet var IPField: NSTextField!  // [A] Set by the user

func triggerRemoteControl(irccc: String) {
    Alamofire.request(IPField,     // [B] Goes here when it's updated.
                      method: .post,
                      parameters: ["parameter" : "value"],
                      encoding: SOAPEncoding(service: "urn:schemas-sony-com:service:IRCC:1",
                                             action: "X_SendIRCC", IRCCC: irccc)).responseString { response in
                                                print(response)
    }
}


}

— UPDATE

I tried declaring a variable:

var IPString: String

and then (I set the textField's delegate to ViewController, and placed this function inside):

override func controlTextDidEndEditing(_ obj: Notification){
    let IPString = IPField.stringValue
}

Even using the "-> String" and return notation still has it complaining about unused variables. I obviously don't know my Syntax well enough.

Complier also complains about not the ViewController not being initialised.


Solution

  • What you need is to override the func controlTextDidEndEditing(_ obj: Notification) function

    You should take a look at:

    • object (property of obj) - sometimes you would like to know which object sent you the end editing action.

    • userInfo (property of obj) - contains a "NSTextMovement" key, which allows you to define how the user did end the editing.

    override func controlTextDidEndEditing(_ obj: Notification){ let IPString = IPField.stringValue }

    Here, you're creating new constant. What you want is to set this value into your class variable, so you should make IPString = IPField.stringValue

    But it's not quite correct, because func controlTextDidEndEditing(_ obj: Notification) could be called from other objects, so first you should check if obj notification contain object which send it with guard, for example.

    guard let object = obj.object else { return }

    Then check if object is your IPField with identity operators

    guard object === IPField else { return }

    And finally you can assign your field value to your IPString var

    IPString = object.stringValue

    Hope it will help you. Ohh and one advice from my side, you should use lower camel case naming convention for you variables.