Daisy
Daisy

Reputation: 121

macOS Swift TextField.stringValue not returning updated value until I click on something else

I apologize if this has been asked before but I couldn't find what I was looking for online over the last few hours. I'm still functional a noob with swift.

I am trying to store the stringValue of a TextField when I click a NSButton. If I click anywhere and then click on the NSButton the code works perfect but if I don't click the stringValue is still reporting the previous value.

@IBOutlet weak var NameText: NSTextField!
@IBOutlet weak var SaveChangesAccountButton: NSButton!

var selectedAccountItemNumber = NSInteger()

@IBAction func SaveAccountChanges(_ sender: Any)
{
    let AccountName = NameText.stringValue

    AccountingData.instance.book.account[selectedAccountItemNumber].name = AccountName
}

Upvotes: 0

Views: 114

Answers (1)

vadian
vadian

Reputation: 285230

You have to call validateEditing() on the text field.

And please conform to the naming convention that variable and function names start with a lowercase letter and don't use NSInteger in Swift.

@IBOutlet weak var nameText: NSTextField!
@IBOutlet weak var saveChangesAccountButton: NSButton!

var selectedAccountItemNumber = 0

@IBAction func saveAccountChanges(_ sender: Any)
{
    nameText.validateEditing()
    let accountName = nameText.stringValue
    AccountingData.instance.book.account[selectedAccountItemNumber].name = accountName
}

Upvotes: 2

Related Questions