Accessing Interface Builder GUI Controls Anywhere in the App

I used the Interface Builder to place a Switch object in a view. I ctrl dragged it into the Assistant to make its handler a method of the class the view's is in, which is itself a subclass of "UITableViewController". A dialog box appear into which I entered the function name, and select the the option to have the sender as an argument.

The result is function of the form:

@IBAction func switchStateChange(_ sender: UISwitch) {        
   }

Now I need to query this Switch's On/Off state from elsewhere in the program, and if necessary change its state. It is not a good solution to save the sender parameter to a global variable because then it would require the user to change this switch's state before that global variable is set.

What is needed is to identify, and lookup, this switch object to access it from anywhere in the application. How is this done?

Accepted Reply

I found my answer here: https://help.apple.com/xcode/mac/current/#/devc06f7ee11

There are at least two ways to do it. The simplest way takes more memory, but it is quick and easy. This is to put an outlet in the class that defines the view the switch is in. The outlet is placed there in the same way the handler method is, namely by control dragging the switch from the Storyboard into its class's code shown in the Assistant. In the dialog that appears when the switch is dropped into the code, instead of selecting "Action" select "Outlet", and enter a variable name. The result will be a line of code of the form:

@IBOutlet weak var mySwitch: UISwitch!

Where in place of "mySwitch" will be the variable name entered into the dialog box, and the class member name the switch's state can be accessed by.

Replies

I found my answer here: https://help.apple.com/xcode/mac/current/#/devc06f7ee11

There are at least two ways to do it. The simplest way takes more memory, but it is quick and easy. This is to put an outlet in the class that defines the view the switch is in. The outlet is placed there in the same way the handler method is, namely by control dragging the switch from the Storyboard into its class's code shown in the Assistant. In the dialog that appears when the switch is dropped into the code, instead of selecting "Action" select "Outlet", and enter a variable name. The result will be a line of code of the form:

@IBOutlet weak var mySwitch: UISwitch!

Where in place of "mySwitch" will be the variable name entered into the dialog box, and the class member name the switch's state can be accessed by.