I am attempting to use a button to go from one View (XIB) to another View. I'm using Xcode 4.3.2 and iOS 5. I start off by creating the project (Single View Application). I then create my button in Interface Builder, create my outlet in the header file, and my IBAction in the .m file. Next, I right clicked on my project folder in Xcode and selected "New File". I then selected "Object-C Class" and named it "SecondViewController". Two new files were created, "SecondViewController.h" and "SecondViewController.m". Then I went back and right clicked on my project folder in Xcode, selected "New File" and chose "view" out of the "User Interface" options.
Now I have my empty IBAction (my button) which I want to use to go to a new view, which is called SecondViewController.xib.
If the creation of the new XIB and .h/.m files are correct up to this point, then how would I go about doing this using my button to "get to" or display my second view? Keep in mind, I'm still at a beginner level and I appreciate any help and your patience 🙂
The only differences I can tell between my main View and my SecondView are in the header files:
Main View header file:
@interface ButtonToNewViewViewController : UIViewController
Second View header file:
@interface SecondViewController : NSObject
IBAction:
-(IBAction)nextView:(id)sender
{
// go to new view
}
Best Answer
This is quite a simple task that are covered by many tutorials online, but I'll give you some help anyways. :-)
First of all, when you create
SecondViewController
, remember to create it as a subclass ofUIViewController
, notNSObject
. So unless you have done a lot of work with those files, you can just go ahead and recreate them. At the same time you can make sure that Xcode creates the xib-file for you automatically by checking a checkbox in the creation-process.When you have created
SecondViewController
(.h, .m and .xib), open upButtonToNewViewController.m
and put#import "SecondViewController.h"
at the top of the file. In your methodnextView:
, you can then use these two lines to change to the second view controller:That should pop up the second view controller, with some simple animation. Make sure that the string you pass to
initWithNibName:
has the same name as your .xib-file.And if you want to go back to
ButtonToNewViewController
, you can use this in a method inSecondViewController
:That should clear things up a bit. :-)