Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How should a UIView get references to its children?

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?

like image 856
Undistraction Avatar asked Jul 20 '12 12:07

Undistraction


People also ask

What method or methods do you call to add a subview to another view?

To add a subview to another view, call the addSubview(_:) method on the superview. You may add any number of subviews to a view, and sibling views may overlap each other without any issues in iOS.

How do I present a UIView in Swift?

present the gray UIView like you would usually present a ViewController (appearing bottom up and user can slide down to dismiss). The bottomBar is a ContainerView and should not change by switching between the VC's, only the gray UIView which you can see in the 2nd picture.


2 Answers

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.

like image 93
Moshe Avatar answered Sep 24 '22 07:09

Moshe


try [view viewWithTag:tagOfChildView];

like image 43
lu yuan Avatar answered Sep 25 '22 07:09

lu yuan