Add UIView on UIViewController - objective-c

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.

Related

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.

Accessing an instance method of a ViewController From Another view controller

Let's say I have a view controller called vc1, which a synthesized property called property1, and i wants to access it from another view controller (vc2) and change it from vc2.
Now the methods created by the #syntisize to change and get properties are instance methods, so how can I get to them fro another view controller (do view controllers have instances in the app, and if so, what are they?)
Just to be clear I am using storyboards, so I never really instantiate the view controllers...
VC1.m:
-(void) yourMethod {
...
}
VC2.m
YOURViewController * vc2 = [[YOURViewController alloc]init];
[vc yourMethod];
[vc release];
Make sure to import your YOURViewController in your other view .m file
Something like that should work.
Or if you're having problems, try this tutorial here:
Tutorial on How-To Pass Data Between Two View Controllers
Hope this helps :)
While you can do it the way you describe, I think the common technique (assuming VC1 has a segue to VC2) is a bit different, where VC2 will have a property that will be set by prepareForSegue. See Configuring the Destination Controller When a Segue is Triggered in the View Controller Programming Guide.
You will need to link the storyboard views with the viewcontrollers so the view for vc1 would use the class vc1 etc for the rest (I assume you have done this because this is important when coding for different views)
Then all you need to do is where ever you are calling the properties so lets say the viewDidLoad method, declare the view controller like this:
- (void) viewDidLoad {
vc1 *viewController;
// Now you change the variable I'll presume its a UILabel so I'll change its text [viewController.property1 setText:#"I changed a different views UILabel"];
}
Let me know whether this works... Its worked for me before so should work

Object mixup between programmatically created view and interface builder placeholder

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?

iPhone subview design (UIView vs UIViewController)

I'm designing a simple Quiz application. The application needs to display different types of QuizQuestions. Each type of QuizQuestion has a distinct behavior and UI.
The user interface will be something like this:
alt text http://dl.getdropbox.com/u/907284/Picture%201.png
I would like to be able to design each type of QuizQuestion in Interface Builder.
For example, a MultipleChoiceQuizQuestion would look like this:
alt text http://dl.getdropbox.com/u/907284/Picture%202.png
Originally, I planned to make the QuizQuestion class a UIViewController. However, I read in the Apple documentation that UIViewControllers should only be used to display an entire page.
Therefore, I made my QuizController (which manages the entire screen e.g. prev/next buttons) a UIViewController and my QuizQuestion class a subclass of UIView.
However, to load this UIView (created in IB), I must[1] do the following in my constructor:
//MultipleQuizQuestion.m
+(id)createInstance {
UIViewController *useless = [[UIViewController alloc] initWithNibName:#"MultipleQuizQuestion" bundle:nil];
UIView *view = [[useless.view retain] autorelease];
[useless release];
return view; // probably has a memory leak or something
}
This type of access does not seem to be standard or object-oriented. Is this type of code normal/acceptable? Or did I make a poor choice somewhere in my design?
Thankyou,
edit (for clarity): I'd like to have a separate class to control the multipleChoiceView...like a ViewController but apparently that's only for entire windows. Maybe I should make a MultipleChoiceViewManager (not controller!) and set the File's Owner to that instead?
You're on the right track. In your QuizController xib, you can create separate views by dragging them to the xib's main window rather than to the QuizController's main view. Then you can design each view you need according to your question types. When the user taps next or previous, remove the previous view and load the view you need based on your question type using -addSubview on the view controller's main view and keep track of which subview is currently showing. Trying something like this:
[currentView removeFromSuperView];
switch(questionType)
{
case kMultipleChoice:
[[self view] addSubview:multipleChoiceView];
currentView = multipleChoiceView;
break;
case kOpenEnded:
[[self view] addSubview:openEndedView];
currentView = openEndedView;
break;
// etc.
}
Where multipleChoice view and openEndedView are UIView outlets in your QuizController connected to the views you designed in IB. You may need to mess with the position of your view within the parent view before you add it to get it to display in the right place, but you can do this with calls to -setBounds/-setFrame and/or -setCenter on the UIView.
Yeah, IB on iPhone really wants File's Owner to be a UIViewController subclass, which makes what you want to a bit tricky. What you can do is load the nib against an existing UIViewController instead of instantiating one using the nib:
#implementation QuizController
- (void) loadCustomViewFromNib:(NSString *)viewNibName {
(void)[[NSBundle mainBundle] loadNibNamed:viewNibName owner:self options:nil];
}
#end
That will cause the runtime to load the nib, but rather than creating a new view controller to connect the actions and outlets it will use what you pass in as owner. Since we pass self in the view defined in that nib will be attached to whatever IBOutlet you have it assigned to after the call.

Design an NSView subclass in Interface Builder and then instantiate it?

So I have an NSTabView that I'm dynamically resizing and populating with NSView subclasses. I would like to design the pages in IB and then instantiate them and add them to the NSTabView. I got the programmatic adding of NSView subclasses down, but I'm not sure how to design them in IB and then instantiate them.
I think I got it. Let me know if this is not a good thing to do.
I made a new xib file, set its File's Owner to be an NSViewController and set its "view" to the custom view I designed in the xib.
Then you just need:
NSViewController *viewController = [[NSViewController alloc] initWithNibName:#"MyViewXib" bundle:nil];
NSView *myView = [viewController view];
#toastie had a really good answer. Mine is similar, but requires a bit more explanation.
Let's say you've already got a controller object and you don't want to instantiate a new controller object just to get at a view, and let's say that you're going to need multiple copies of this view (for example, you've designed a custom UITableViewCell in IB and you want to instantiate it again and again from your UITableViewController). Here's how you would do that:
Add a new IBOutlet to your existing class called "specialView" (or something like that). It may also be helpful to declare it as a (nonatomic, retain) property.
Create a new view xib called "SpecialView", and build the view however you like.
Set the File's Owner of the view to be your controller object.
Set the specialView outlet of File's Owner to be the new view.
Whenever you need a new copy of the view in your code, you can simply do the following.
(gratuitous text to get formatting working properly)
NSNib * viewNib = [[NSNib alloc] initWithNibNamed:#"SpecialView" bundle:nil];
[viewNib instantiateNibWithOwner:self topLevelObjects:nil];
[viewNib release];
NSView * myInstantiatedSpecialView = [[[self specialView] retain] autorelease];
[self setSpecialView:nil];
Yes, it's a bit more code than other ways, but I prefer this method simply because the view shows up in the designated IBOutlet. I retain and autorelease the view, because I like to reset the outlet to nil once I have the view, so it can be immediately ready to load a new copy of the view. I'll also point out that the code for this is even shorter on the iPhone, which requires one line to load the view, and not 3 (as it does on the Mac). That line is simply:
[[NSBundle mainBundle] loadNibNamed:#"SpecialView" owner:self options:nil];
HTH!