How to reference a subview from another in the view hierarchy programmatically?

584 views Asked by At

I have a (simplified) Cocoa view hierarchy as follows:

window
- contentView
-- view1
---> button1
--view2
---> textField1

Importantly, the button1 & textField1 do NOT share an immediate superView.

I would like to add a target-action to button1 to perform something (not relevant what precisely) on textField1 (consider textField1 is some custom text field I have created).

In my understanding, the button will have to have a reference to textField1 at initialization so that you can add the "target-action".

My question is what is the best way for button1 to get hold of this reference in a manner that will scale to more complex/deep/nested view hierarchies

I am hopefully looking for something a little more elegant than:

let reference = self.superview.subview[0].subview[0] as NSView

Interface Builder allows you to right-click and drag from the button to the textField to make a 'connection' and it uses some sort of internal ID for this. Is their something similar to be done in code?

1

There are 1 answers

3
bandejapaisa On BEST ANSWER

The two views wouldn't have a reference to each other at all. That doesn't scale well. That would be akin to a UITableView always having a reference to a UITextField.

Your views should be just displaying stuff. You need a controller, or more specifically the View Controller to let them interact, via a Model if you desire.

There are many ways to do this, but the guiding principle is that they are decoupled. The button would have an action. That action could have a target method on the view controller, it could fire a NSNotification,... the ViewController would handle this and then do something with textfield on the other view.

Maybe the button changes some data in your Model, and the textfield is somehow wired up via it's controller to listen for changes to the Model and display the data via the Model.

Just keep your view displaying stuff. Don't put Model stuff in the views. Let the controller manage the coordination of letting your views communicate.