Object mixup between programmatically created view and interface builder placeholder - objective-c

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?

Related

How to set UITableViewController custom class programmatically?

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"];

Link XIB to a custom NSView in a Framework

I am writing a Cocoa Framework (not an Application), it contains the definition of a customized NSView; the framework will be loaded in other applications, and the customized NSView will be dragged to the GUI of the applications and become initialized
The question is that I want to include a XIB file in the Framework
I want to add a button and a label to the XIB (in the framework), but the view in the application that consumes the framework, won't show the button and the label
I already set the File's Owner of XIB to the custom NSView in the framework
What else should I do?
Have the view load the nib and move the button, label, etc., from the view in the nib to itself.
It'll be easiest to do this just by getting the subviews of the nib's view and doing this for all of them.
If your nib uses Auto Layout, I think you'll also need to bring across any constraints owned by the nib's view, and you may also need to edit or replace any constraints that refer to that view (e.g., if a view is set to be X points away from an edge of the nib's view).
You may also need to do extra work to change the new view's frame, or to change the frames of the subviews (whether by relocation, resizing, or both) to match the frame given for the new view.
Yeah, I just solved the issue, and I hope the details are helpful to others.
In the framework, there is a complicated subclass of NSView, which contains many controls such as NSSplitView NSOutlineView and IKImageBrowserView, NSPathControl and etc; the framework contains a H file, a M file and a XIB file; H and M define the MyView class; in the XIB, there is a View object whose class is MyView.
On the application side, users need to drag a NSView item onto the main window of their app, and assign an outlet to the view, let's say mainView, and in the applicationDidFinishLaunching function of the "consumer" app, the follow code is necessary
NSBundle *frameworkBundle = [NSBundle bundleForClass:[MyView class]];
NSNib *nibby = [[[NSNib alloc] initWithNibNamed:#"MyView" bundle:frameworkBundle] autorelease];
NSArray *topLevelObjects = nil;
BOOL flag = [nibby instantiateNibWithOwner:nil topLevelObjects:&topLevelObjects];
assert(flag);
for (id topLevelObject in topLevelObjects) {
if ([topLevelObject isKindOfClass:[MyView class]]) {
[mainView addSubview: topLevelObject];
MyView* xView = topLevelObject;
[xView setFrameSize:mainView.frame.size];
break;
}
}
In the code above, the XIB files is loaded, thus the MyView object is initialized, then we fetch it out of the XIB, resize it and add it to the main view of the window

Static UITableView not fullscreen

For my registration form, I am currently using a UITableView which isn't fullscreen and I add cells programmatically through hardcoding the datasource methods. By the time the whole class got very complex and huge.
Pastebin link
The cells are custom and have a UILabel and a UITextfield. Now one of the cells should have a button instead of the textfield. This would make the whole thing more complex then it should be, in my opinion. So my thought was using the static feature of the tableview in the storyboard. But this requiers a UITableViewController, if I use one the TableView is always fullscreen. Is there a way to se the static feature without a fullscreen TableView??
If you have a fixed number of cells, the static table view controller is a good option. Instead of implementing the datasource methods, as you mentioned, you can include each input field as an IB outlet.
If you want a static table view controller that is not full-width, embed the table view controller inside a container view.
For example, create a new view controller, add a container view object w/ the desired width in this new view controller, and then connect your static table view controller to the container view.
Note that the static table view controller becomes a childViewController of the enclosing view controller. You can facilitate access to the textFields from the enclosing view controller w/ a weak property to the textFields w/in the child view controller.
- (UITextField *)surnameTextField
{
UITextField *textField;
// reference childController that is initiated via containerView
if ([[self.childViewControllers lastObject] isKindOfClass:[NameViewController class]])
{
NameViewController *nameVC = [self.childViewControllers lastObject];
textField = nameVC.surnameTextField;
}
return textField;
}
You do not need to use a UITableViewController. Just drag and drop a table view from the control palette onto a UIViewController in your storyboard. Size and position it how you want to and add any other controls to the UIViewController that you need.
In the property sheet for the UITableView set the content type to 'Static Cells' then define your cells how you want them.

Change the custom class in a storyboard using code when instantiating

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.

Add UIView on UIViewController

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.