I have a tab bar controller and a bunch of the same tabs. Each tab only differs in functionality, but the UI's are all the same. In the storyboard I designed the flow and UI of one tab and set it base class. Then when I create the tabs I tried typecasting them before adding them to the tab bar but it didn't work.
In the storyboard the View Controller indentified "TabView" has the custom class "TabColor"
TabRed *red = (TabRed *)[storyboard instantiateViewControllerWithIdentifier:#"TabView"];
TabBlue *blue = (TabBlue *)[storyboard instantiateViewControllerWithIdentifier:#"TabView"];
However the loadView method in TabColor gets called, not the TabRed/TabBlue.
Also if I nslog it the result is a TabColor object:
NSLog(#"%#", red)
Expected: TabRed
Actual: TabColor
tl;dr:
Storyboards and xibs contain collections of serialized objects. Specifying a class in a storyboard means you will get an instance of that class when you load the storyboard. A way to get the behavior you're looking for would be to use the delegation pattern common in cocoa/cocoa-touch.
Long Version
Storyboards, and similarly xib/nib files, are actually sets of encoded objects when you get down to it. When you specify a certain view is a UICustomColorViewController in the storyboard, that object is represented as a serialized copy of that an instance of that class. When the storyboard is then loaded and instantiateViewControllerWithIdentifier: gets called, an instance of the class specified in the storyboard will be created and returned to you. At this point you're stuck with the object you were given, but you're not out of luck.
Since it looks like you're wanting to do different things you could architect your view controller such that that functionality is handled by a different class using delegation.
Create a protocol to specify the functionality you'd like to be different between the two view controllers.
#protocol ThingDoerProtocol <NSObject>
-(void) doThing;
#end
Add a delegate property to your viewcontroller:
#interface TabColor
...
#property (strong, nonatomic) thingDoerDelegate;
And then have your new objects implement the protocol and do the thing you want them to.
#implementation RedTabDoer
-(void) doThing {
NSLog(#"RedTab");
}
#end
#implementation BlueTabDoer
-(void) doThing {
NSLog(#"BlueTab");
}
#end
Then create and hook up those objects when you load the storyboard.
TabColor *red = [storyboard instantiateViewControllerWithIdentifier:#"TabView"];
red.thingDoerDelegate = [[RedTabDoer new] autorelease];
TabColor *blue = [storyboard instantiateViewControllerWithIdentifier:#"TabView"];
blue.thingDoerDelegate = [[BlueTabDoer new] autorelease];
This should then allow you to customize the functionality of the view controller by changing the type of object that is assigned to the controllers delegate slot.
TabRed *red = (TabRed *)[storyboard instantiateViewControllerWithIdentifier:#"TabView"];
TabBlue *blue = (TabBlue *)[storyboard instantiateViewControllerWithIdentifier:#"TabView"];
Casting doesn't change values, it only changes the way the compiler interprets those values (and stops it from complaining when you use type in place of another). So casting a TabColor* to a TabRed* tells the compiler to pretend that your first pointer points to a TabRed instance, but it doesn't transmogrify the object that the pointer refers to into an instance of TabRed.
As waltflanagan explains, storyboards and .xib files contain actual objects, and the type of each object is determined when you create the file; you can't change it at run time. What you can do, though, is to have each of your several view controllers load the same view hierarchy. You don't even have to write any code to do this. Just create a .xib file containing your tab controller and the view controllers for each tab:
Be sure to set the type for each view controller appropriately in the .xib so that the right kind of view controller will be created for each tab:
Set the "NIB Name" field for each view controller to specify a .xib file that contains the view hierarchy that these controllers will use. If you specify the same .xib file for each controller, each controller will instantiate its own copies of those views:
Specify any IBOutlets in the common superclass of your view controllers so that all your view controllers have the same outlets. You can specify that superclass as the type of "File's Owner" in the common .xib file so that IB knows what outlets are available. File's owner is really a proxy for the object that's loading the .xib, so when one of your view controllers (TabRed for example) loads the common view .xib, that controller will be the one that the views in the .xib are connected to. When TabBlue loads the .xib, that object will be the one that those views are connected to.
This might seem confusing at first, but play with it. Understanding this will really help you understand .xib files (and therefore storyboards). They're a lot less magical than they seem when you're a beginner, but once you get it they'll seem even cooler.
Related
This is my storyboard:
The UITableViewController, has a generic UITableCell (MMSwitchTableCell) that has an image, a label and switch.
The idea is to be able to create different UITableViewControllers that present different data with the same layout i.e with the same cell object and same behavior. for example one time the UITableView has a list of cells that helps you select fruits, second UITable helps you select furniture.
The two UITablesViewController have no relation between them (no inheritance or aggregation), they are different instances in different viewControllers, I only want to re-use the designed control and the UITableCell code.
So my code has a UIViewController where I declare a property:
#property (strong, nonatomic) MMGoSeePopoverTableViewController* goSeePopoverTableViewController;
and lazy load it:
-(MMGoSeePopoverTableViewController*) goSeePopoverTableViewController
{
if(_goSeePopoverTableViewController == nil)
{
_goSeePopoverTableViewController =(MMGoSeePopoverTableViewController*)
[self.storyboard instantiateViewControllerWithIdentifier:#"switchPopover"];
}
return _goSeePopoverTableViewController;
}
and a second UIViewController in which I declare a property:
#property (strong, nonatomic) MMLayersPopoverTableViewController* layersPopoverTableViewController;
and lazy load it:
-(MMLayersPopoverTableViewController*) layersPopoverTableViewController
{
if(_layersPopoverTableViewController == nil)
{
_layersPopoverTableViewController =(MMLayersPopoverTableViewController*)
[self.storyboard instantiateViewControllerWithIdentifier:#"switchPopover"];
}
return _layersPopoverTableViewController;
}
In the storyboard I've set the custom class to MMLayersPopoverTableViewController, instead I wish to leave it blank and somehow set it in the code. I guess I should do this inside the lazy loaders, but I can't figure how.
Edit
The suggested "This question may already have an answer here:" is not the same as what I'm asking. I have amended the post to explain my problem better.
The idea is to be able to create different UITableViewControllers that
present different data with the same layout i.e with the same cell
object & same behavior.
This sounds like a case where you should use a .xib file instead of a storyboard. The advantage of storyboards compared to .xib files is that you can see the structure of the app in terms of views and the corresponding view controllers. In your case, though, you're trying to reuse the same view with different view controllers. Putting your table in a .xib file that's owned by the view controller will let you load the same table, cell, etc. with whatever view controller you decide to instantiate.
In your .xib file, set the type of the File's Owner proxy to some common superclass of all your view controller classes which contains all the necessary functionality. For example, if all your view controllers are derived from UITableViewController and you don't need any special outlets, set the type to UITableViewController and connect the table to the proxy's tableView outlet. If your view controllers have other common behavior, put all that in a subclass of UITableViewController, use that as the proxy's type, and derive the other view controllers from that class.
Once you've done all that, you can use the -initWithNibName:bundle: method to initialize any of your view controllers and load the same view:
// in one place...
MMGoSeePopoverTableViewController *goSeeVC = [[MMGoSeePopoverTableViewController alloc]
initWithNibName:#"CommonTableView.xib" bundle:nil"];
// and in some other place...
MMLayersPopoverTableViewController *layersVC = [[MMLayersPopoverTableViewController alloc]
initWithNibName:#"CommonTableView.xib" bundle:nil"];
iOS 5 adds a nice feature allowing you to nest UIViewControllers. Using this pattern it was easy for me to create a custom alert view -- I created a semi-transparent view to darken the screen and a custom view with some widgets in it that I could interact with. I added the VC as a child of the VC in which I wanted it to display, then added its views as subviews and did a little animation to bring it on the screen.
Unfortunately, I need to support iOS 4.3. Can something like this be done, or do I have to manage my "alert" directly from the VC in which I want to display it?
MORE INFO
So if I create a custom view in a nib whose file owner is "TapView" and who has a child view that is a UIButton. I tie the UIButton action to a IBAction in TapView.
Now in my MainControllerView I simple add the TapView:
TapView *tapView = [[TapView alloc] init];
[[self view] addSubview:tapView];
I see my TapView, but I can't interact with the UIButton on it and can interact with a UIButton on the MainControllerView hidden behind it. For some reason I am not figuring out what I'm missing...
Not sure if this helps, but, in situations where I've needed more control over potential several controllers, I've implemented a pattern where I have a "master" controller object (doesn't need to be descendent from UIViewController), which implements a delegate protocol (declared separately in it's own file), and then have whatever other controllers I need to hook into declare an object of that type as a delegate, and the master can do whatever it needs to do in response to messages from the controllers with the delegate, at whatever point you need; in your case, that being displaying the alert and acting as it's delegate to handle the button selection. I find this approach to be very effective, simpler and usually cleaner. YMMV ;-)
Regd. your second query, where you are trying to create a custom view using nib. Don't change the FileOwner type, instead set "TapView" for the class property of the top level view object.
Once you have done this, you might experience difficulty when making connections. For that just manually choose the TapView file for making connections.
Also, to load the view you need to load its nib file. For which you can create a class level helper method in TapView class like below
+(TapView *) getInstance
{
NSArray *bundle = [[NSBundle mainBundle] loadNibNamed:#"TapView" owner:self options:nil];
TapView *view;
for (id object in bundle) {
if ([object isKindOfClass:[TapView class]]) {
view = (TapView *) object;
break;
}
}
return view;
}
Now, you get a refrence to you view object like this
TapView *tapView = [TapView getInstance];
I have a view controller which contains a scroll view. Inside the scroll view there is another UI core graphics view. In the view controller I create a temp object for the core graphics view and assign some data to it, then assign it to the attribute of the view controller. Eg: In the view controller:
#interface controller : UIViewController {
GraphView *graph;
}
#property ... IBOutlet GraphView *graph;
#implementation
GraphView *temp = [[GraphView alloc] init];
temp.someArray = anExistingDataArray;
self.graph = temp;
In IB, I open the view controller nib and add a scroll view, and embed a view and assign it the core graphics view class. Then hook up the IBOutlet from that view to the attribute in the view controller.
My problem is that the view controller creates the temp view object, assigns it to itself, with the correct data, however IB seems to instantiate its own object (different memory ID) and displays that, instead of the one in the view controller.
What is the correct way to build this type of setup?
If you drag an object into a nib, IB creates and archives that object. This is why you don't have to alloc/init views that you create in IB.
I'm guessing that you are creating your view in IB so that you can get the geometry correct, or...? It's rather unusual to create a view and then immediately replace it at run-time. More common, for geometric purposes, is to create a container view in IB and then add your programmatically-created views as subviews of that.
Your code left out the most important piece of this, though, which is when it's getting run. Is it in -init...? -awakeFromNib? -loadView? -viewDidLoad? The exact location matters since these occur in a well-defined sequence. If you put your code in the wrong place, it will run before the nib is unarchived and fully reconnected, so the nib will clobber whatever your code did.
So: when is your [self setGraph] (I can't bring myself to use dot syntax) code getting run?
I would like to update the UI in my application from the AppDelegate, but whenever I call it as so:
Controller *object = [[Controller alloc] init];
[object methodHere];
It doesn't seem to update the UI. What am I doing wrong here? I have put in a NSLog to see if it was being called, and it is. Here is a sample project that shows the error.
Edit: Can someone just show me what to change to the project I provided. I just don't know what to type into my project so that I can change the value of a simple NSTextField from another class.
When you write [[Controller alloc] init], you are not accessing the Controller object that is in your nib. You are creating a new Controller object that is unconnected to anything else in your application.
Remember, every Controller object is not the same any more than every NSArray is the same. Just because you made one Controller in your nib that's connected to an NSTextField does not mean some random Controller that you just created shares that controller's connections.
What you need to do is give the delegate a reference to the Controller that's in the nib.
This is really simple, and Chuck's comments basically explain what you need to do, but I will lay out the code explicitly for you. In testAppDelegate.h:
#interface testAppDelegate : NSObject <NSApplicationDelegate> {
NSWindow *window;
// You can make an IBOutlet to any kind of object you
// want; it's just a way for you to get a reference
// in code to an object that has been alloc'd and
// init'd already by the xib mechanism.
IBOutlet Controller *controller;
}
Then go into your xib in InterfaceBuilder and hook up that outlet from your Test App Delegate object to your Controller object (these objects are already present in the xib).
In testAppDelegate.m:
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
// This is the key:
// _Don't_ alloc/init a new controller object. The
// objects in your xib are allocated and initialized
// by virtue of being in that file. You just need to
// give your AppDelegate a pointer to it, as above.
[controller setTextValue:#"hello"];
}
It's being called all right, but it's not connected to the interface. There should be a view controller of some sort defined in your appDelegate.h file, call the method on that object instead.
Update for more detail:
One way you could pull this off would be to simply save the Controller when you originally create it (and not release it until later.)
Simply put your own controller object into your .h file
Controller* myController;
And when you create the new view controller you want to flip to, simply set myController to reference that object, and later when you want to update the UI, simply call
[myController methodHere];
A bit clumsy, but it works. Just don't forget to release myController when you're done with that view.
The other idea I'd suggest looking into would be to alter the method you're passing to your delegate. That is, instead of having the method as
-(returnType)callDelegateToDoSomething;
put it in as
-(returnType)callDelegateToDoSomething:(id) sender;
You call the new method the same way, but your controller should automatically pass itself as an argument. Then, inside the method, simply use
[sender methodHere];
and it should hopefully work. (You may need to play around with it a little. I'm not an expert on delegates or the sender argument, but it's worth a shot.)
I want to add a "custom" uiview onto a uiviewcontroller, this custom view i created with xib and its a seperate from the view controller,
does anyone know how to add a uiview with a xib into a uiviewcontroller?
Many thanks in advance
You mean an additional view, not the main controller view? In that case you can declare a property for the view and load the NIB by hand:
#interface Controller {}
#property(retain) IBOutlet UIView *extraView;
#end
…
- (void) viewDidLoad // or anywhere else
{
[[NSBundle mainBundle] loadNibNamed:#"extras" owner:self options:nil];
NSAssert(extraView != nil, #"The extra view failed to load.");
[[self view] addSubview:extraView];
}
This assumes that you set the Controller as the file owner in the Interface Builder and you link the view to the extraView outlet. Also note that there might be more elegant solutions, like inserting the extra view into the main NIB for your controller; depends on the situation.
It looks like you want the most common scenario – simply load an intialized custom UIView subclass into a controller.
Create a new XIB, called “View XIB” in the Xcode new file wizard.
In the Interface Builder select the File Owner object and on the Object Identity tab in the Object Inspector (Cmd-4) enter Controller (or however your controller class is named) into the Class field.
Do the same with the view, entering the name of your view class.
Ctrl+drag from the file owner to the view, you should be able to connect the view to the view outlet defined on your controller.
Save, let’s say Controller.xib.
In your code, initialize the controller using initWithNibName:#"Controller" bundle:nil. The initialization code should load the interface for you and set the view property to the view unpacked from the interface file.
Go through some Interface Builder tutorial, IB is a very nice tool and it’s good to be familiar with it.