Assigning classes to storyboard view controllers (Xcode for iOS 5 onwards)

To create new view controllers in an iPad or iPhone storyboard requires simply a drag and drop from the object menu, and as was described in the seven steps to segue post it is incredibly easy in iOS 5 to link one view controller to another.  However, there is one important step for enabling control of the content of a view controller created in this way and that is to ensure that it is assigned to the class that are you are going to use to control it. In this post I describe how to do this and provide a simple exercise for testing that it is performing correctly. Having created your new View Controller in the Storyboard, next go to the file menu and create a pair of .h and .m UIViewController subclass files

but for now deselect "With XIB for user interface" from the dialogue box.


Now use the Identity Inspector in the right-hand menu bar, and with the whole of the new view controller highlighted (not just one element of it!) you can select the Custom Class that you just created.
You can test this is working by dragging out a simple label and connecting an outlet to the header file. Do this by double-clicking on the view of the new view controller to zoom in, then pressing the Assistant Editor button. After which you need to drag out a label from the objects onto your view controller and Ctrl + drag from the label to your header file.



When prompted give the outlet a name so it looks like this


We are then ready to write a little bit of code to test the theory in your view controller's .m file.

To the method

- (void)viewDidLoad


add within the curly braces 

labelTest.text = @"Hello World";


beneath
[super viewDidLoad];


You'll also need to add

@synthesize labelTest;

beneath the implementation instruction that in the .m file begins

@implementation

and is followed by your (sub)class name.

Finally, so that our app opens on this ViewController and not the other one we need to make one final adjustment to the MainStoryboard.storyboard file. Have you noticed the arrow pointing to the left side of the first view controller? We need to drag and drop this arrow so that it points to our new view controller like this:

The arrow determines the root view controller. All should build and run fine now. Try it.


Endorse  on Coderwall

Comments

  1. This is my first time pay a visit at here and i am in fact impressed to read all at single place.
    storyboard

    ReplyDelete

Post a Comment