Tutorial :Accessing Views created in Interface Builder



Question:

I've created a ChildViewController class, and then a nib that uses that class.

Then I created a BaseView, that includes some buttons, and some text that I'll be changing programmatically.

Then I created two more views (Boy and Girl), that I want to be able to lay behind the baseview so that the background color is different along with some graphics in an ImageView. I've named the views that I created in IB 'Boy' and 'Girl'...

But when I go back to my code where I'm calling ChildViewController, I'm not sure how to access the views I created so I can call insertSubView. Do I need to instantiate them in code? (in ViewDidLoad perhaps?) Does the nib create the instances when it loads?

I'm confused about how to handle multiple views for a single ViewController

edit =================

@Pablo Santa Cruz

Your answer assumes that i have two nibs and two view controllers (one for each view). I want to know if I can use one nib and one controller, and load in UIViews. It seems silly to create another nib and controller, when all want to do is change the background color and some graphics. Can't I programatically load in UIViews into a UIViewController?


Solution:1

Add IBOutlets in your App Controller class in Xcode then link them in IB (ctrl-click or right-click) from the connections tab in the Inspector to the object.

Then you will be able to send method calls to the objects.

The code in Xcode should look like this:

@interface AppController : NSObject  {     IBOutlet Girl girlIvarName1;     IBOutlet Boy boyIvarName2;  }      @end  


Solution:2

You can access a UIView programatically by assigning a value to its tag property, which can be set in IB on the first tab of the inspector (Command 1)

The tag value defaults to zero, so if you want to access it specifically, make it non zero and unique. e.g. 100, which I will use in the example code below

Once the tag is set you can access the view using the following code in your UIViewController that was initWithNibName for the NIB containing the tagged view

UIView *aView = [self.view viewWithTag:100];  


Solution:3

You can get instances for your IBuilder views with this piece of code:

boyViewController = [[BoyViewController alloc] initWithNibName:@"BoyViewController" bundle:nil];  girlViewController = [[GirlViewController alloc] initWithNibName:@"GirlViewController" bundle:nil];  

Assuming your NIB file names are BoyViewController and GirlViewController. With those instances, you can do whatever you need to. I.E., adding them to a parent view (with addSubView message on the parent).


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »