How should a UIView get references to its children?

Undistraction picture Undistraction · Jul 20, 2012 · Viewed 9.8k times · Source

I have a xib with a root view that is a UIView subclass. How should this view get references to the child views I declared in Interface Builder?

Obviously a ViewController can be wired up with outlets, but what about a UIView?

Answer

Moshe picture Moshe · Jul 20, 2012

Outlets are properties of UIViewController objects which (almost always) refer to instances of UIView objects (or subclasses of UIView).

A UIViewController has a single UIView which, when the UIViewController is loaded with initWithNibNamed:, is the contents of the XIB file. You can set up outlets in the UIViewController and then tie them to the various subviews in your XIB by dragging to the "File's Owner" item in the list, or by dragging to the code in Xcode's assistant editor.

If you want to use only code, there are several options. One way, is to directly access a view based on its tag property. For example:

[myView viewWithTag:42];

Another approach to consider is that a UIView has a property called subviews, which is an array of sub views. You can iterate through them and access the views as necessary. To differentiate between them, you can do several things, depending on the situation. You can set tags on the views, and just use those.

NSArray *subviews = myView.subviews;

for(UIView *view in subviews){
  if(tag == 42){
    // Do something with that view
  }
}

Alternatively, if you're looking for a specific kind of view, say, a UISwitch, something like this might work in simple cases:

for(id view in subviews){
  if([view isKindOfClass:NSClassFromString(@"UISwitch")]){
    // Do something with that view, since it's a switch 

  }
}

If you're using tags, you can set them in code, or use Interface Builder.