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?
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.
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.
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.
try [view viewWithTag:tagOfChildView];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With