Tom el Safadi
Tom el Safadi

Reputation: 6776

Get reference to current object

My goal is to safe a reference from the button, label or textfield inside a variable. The problem is that I don't know on which control the user tapped. I am having a simple application which looks like this:

enter image description here

The user can touch any control.

It is easy enough with just those three controls because I can drag in a action. But if I am having many of them I can't handle them all over the action methods. Is there a general way in which I can safe a reference to the control in a variable so that I can know which of the controls is the active one?

Edit

As suggested I am using a function and assigning the variable to the sender of the function. This is how it looks in code:

var currentObject: NSTextField!

override func viewDidLoad() {
    super.viewDidLoad()

    myTextfield.action = #selector(myAction)
}

func myAction(sender: NSTextField)
{
    print("aktuell: \(sender)")
    currentObject = sender
}

As you can see this only works for a NSTextfield. Is there a way in which the function works for every control?

Upvotes: 0

Views: 242

Answers (1)

sschale
sschale

Reputation: 5188

Set the tag attribute for each item, and then you can check sender.tag to identify which object is calling it.

To set the tag, select the Attributes inspector in Storyboard (upper right side - middle button of Utilities) and look for this section:

enter image description here

Upvotes: 1

Related Questions