Can multiple container scenes use a common view controller? - ios

I've got four scenes in my storyboard. One scene is acting as the parent to all the others via container views. Everything is arranged like so:
If you squint, you'll notice that all four are subclassed from the same view controller. I did this so that I could connect each scene's elements to a single, common view controller and avoid subclassing UIViewController four times. The ProductDetailViewController implementation looks like this:
#implementation ProductDetailViewController {
// Scene 1
__weak IBOutlet UINavigationBar *_navigationBar;
// Scene 2
__weak IBOutlet UILabel *_productName;
// Scene 3
__weak IBOutlet UILabel *_typeNameLabel;
__weak IBOutlet UILabel *_categoryNameLabel;
__weak IBOutlet UIImageView *_richImage;
// Scene 4
__weak IBOutlet UIImageView *_productImageView;
}
The problem is that viewDidLoad fires four times (obviously) and things are showing up blank. When I step through the debugger, the product object I'm passing around is nil for three cycles and then initializes on the fourth. Maybe the view controllers are loading out of order?
In any case, is this setup even ok to do? I'm thinking there's got to be a better way to avoid a subclassed view controller for every storyboard scene.

Setting multiple .xibs to be the same class is common. Not wanting to subclass UIViewController four times is also common.
One problem is that by doing this with Child View Controllers embedded in a Parent View Container and all the same View Controller class, you are creating four instances of the class that are all different and when writing you can't assume anything about which one you are. No wonder the product object is getting lost.
This structure can be salvaged, and it has a lot to recommend it, but it will take some arrangement. A good way is for the parent-delegate to make all the decisions.
Give the class a delegate property, of its own kind, of course weak (weak because the child can't keep the parent alive). Throughout, this you can check to see if it's nil, because if it has a delegate it's a child, but if it has no delegate it's a parent. You usually don't need to know, though.
Use Segue Identifiers. In IB, give each of those embed segues an identifier. Then, in your View Controller class, implement prepareForSegue:sender: with the body
if ([segue.identifier isEqualToString:#"ProductNameIdentiferInStoryboard"]) {
/*...*/ }
else if ([segue.identifier isEqualToString:#"typeBarIdentiferInStoryboard"]) {
/*...*/ }
else if ([segue.identifier isEqualToString:#"productImageIdentifierInStoryboard"]) { /*...*/ }
Implement three properties, again of the same kind, each representing a childViewController,
#property ProductDetailViewController *productNameViewController;
#property ProductDetailViewController *productTypeBarViewController;
#property ProductDetailViewController *productImageBarViewController;`
In prepareForSegue from step 2, fill in with the pattern:
self.productNameViewController = segue.destinationViewController;
self.productNameViewController.delegate = self;
Note prepareForSeque:sender: fires before any viewDidLoad, so you have the references: do all the setup here from the parent's point of view. self.productNameViewController.titleLabel.text = #"Product Name"; The children will fire first, regardless sending a message to nil does nothing, so it's fine they play with their imaginary children. They have a delegate if they need to send information up or ask something important.
This may seem cumbersome, and the identifier stuff definitely is. However, the benefits of keeping centralized control in the code while working with spread out layouts in IB are obvious as a way to handle view controllers.

You definitely can have a single view controller class shared by these four scenes, but there will be four instances of that view controller class, not one.
Having said that, I would advise against this approach and I would suggest either:
Keep the storyboard layout you have, but use a unique view controller class for each child scene, each with its own unique IBOutlet references.
If you'd like the parent view controller to have access to data entered in the child view controllers, you can obviously have the child view controllers update the parent view controller (e.g., using delegate-protocol pattern). But I wouldn't personally expose the child's UIKit properties to the parent view controller (a view controller has no business accessing the UIKit objects of another controller's view), but rather pass back the model data.
If you don't want separate controllers, just don't put these child views in separate scenes. Your example does not appear to be a very compelling use of view controller containment, anyway. In my mind, those child scenes would have to have some reasonable degree of complexity to justify the use of a separate scene (and thus justify separate view controllers). If they're not that complicated, you'd just add subviews to the parent view controller, which is much easier, rather than using container views and the view controller containment that entails.

Related

What is the difference between a UIView outlet, and a ChildViewController?

Lets say I have a container view in a parent UIView.
What is the difference between referencing it as an Outlet in my parent UIView, or accessing it this way :
categoryContainerViewController = self.childViewControllers[0] as! CategoriesControllerView
View and view controllers are two different things
A VIEW is an object that is drawn to the screen. It may also contain other views (subviews) that are inside it and move with it. Views can get touch events and change their visual state in response. Views are dumb, and do not know about the structure of your application, and are simply told to display themselves in some state.
A VIEW CONTROLLER is not drawable to the screen directly, it manages a group of view objects. View controllers usually have a single view with many subviews. The view controller manages the state of these views. A view controller is smart, and has knowledge of your application's inner workings. It tells the dumb view objects what to do and how to show themselves.
now you can get idea about View and a view controller.
A view and a view controller are two totally different things.
categoryContainerViewController = self.childViewControllers[0] as! CategoriesControllerView
In spite of the name, that is a view controller.
The outlet is to the view.
In layman terms : -
IBOutlet connects any view element from your interface builder to attached swift class file. So you can get reference to any subview of UIView(eg, UILabel, UIButton) from interface builder to your UIViewController or UIView Swift class
In your ex.
by using
categoryContainerViewController = self.childViewControllers[0] as! CategoriesControllerView
You are getting reference to your ChildViewController and not any view

Connecting Objects with two View controllers in Swift

In my project I have two view controllers, and I am having trouble connecting objects such as an UIImageView to the view controller. When I try to create the IBOutlet, it tells me that "Could not insert new outlet collection: could not find any information for the class named UIViewController". I believe this problem stems from the fact that my original declaration of my class is as follows:
class UIViewController: UIViewController {
when in fact the view controller is named mainScene instead. However, when I change the first UIViewController to what I think it should be (mainScene), it doesn't even show me the option of connecting an IBOutlet...
class mainScene: UIViewController {
So, I have two questions.
Do I need to have a whole separate class for the second UIViewController and would that solve my issues?
Is there a better way to link objects to the UIViewController or am I just doing something horribly wrong (the likely scenario)?
Thanks so much
Short answer: 1. Yes, and yes. 2. There's no better way, and you're not doing something horribly wrong. (You probably just missed a step.)
You have two view controllers. Assuming they are different, you would subclass each one from UIViewController with a different name. E.g., mainSceneViewController and otherSceneViewController.
Your mainSceneViewController and otherSceneViewController would each have their own properties and IBOutlets.
Where you're probably stuck, is needing to change the class of your viewController within Interface Builder to match the class name in its .swift file, so IB knows what outlets it can connect for that view controller.
Each scene in your storyboard corresponds to a view controller. When the segue is performed, iOS instantiates your view controller from the storyboard.
While it is possible to only have one view controller subclass, and use the same subclass for different views, it doesn't happen too often.
Update:
Subclassing lets you add properties and methods to a class, and override their superclass.
In your comment, UIViewController is the class, and mainSceneViewController is subclassed from UIViewController. For your second view controller, it would likely be class otherSceneViewController: UIViewController {, as your other scene would likely require a different properties and methods from your main scene view controller.
You can read more about Inheritance in the Swift Programming Language guide.

Multiple 'nibs' per UIViewController

I'm using storyboards and I want two UIViewControllers to share the same controller class. I've done this and I've hooked up my UIImageViews to their IBOutlets.
When I call [day3 setImage:[UIImage imageNamed: #"1.png"]];
it doesn't change the image. Has this got anything to do with it sharing the same controller class as another view?
This view with the UIImageViews on is opened via push segue from the other view controlled by the same controller class.
Your problem is that although both views are using the same UIViewController, they are connected to different instances of them. Let's call our ViewController myViewController. When the new view is pushed it actually creates a whole new myViewController. So you now have two active in your app. One instance of myViewController for the first view and another for the second view. You can therefore not directly manipulate the views from the other view's instance of that controller.
In order to set properties you will need to communicate between the two instances of myViewController the same way you would as if they were entirely different ViewControllers. If you need further help or explanation let me know.

Linking child view controllers to a parent view controller within storyboard

Can you associate child view controllers to a custom container view controller in Storyboard?
I can link child view controllers to a tab view controller, and I can link one view controller to a navigation controller.
What must I do to the container VC to accept child VCs?
As something of a combo of Caleb and Matt's answers, I did:
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
if ([segue.identifier isEqualToString:#"cpdc_check_embed"]) {
self.checkVC = segue.destinationViewController;
}
}
...where checkVC is a property on the container controller:
#property (weak,nonatomic) PXPCheckViewController * checkVC;
You just have to set your embed segue's Storyboard ID to whatever you want (in this case, cpdc_check_embed):
...and then check the identifier in -prepareForSegue:sender:.
Still not an outlet, but cleaner than Matt's (IMHO) and more specific than Caleb's, and you still get a nice-looking storyboard:
The storyboard deals with built-in container view controllers very nicely, displaying segues to child/root view controllers so that relationships are clearly shown. It is also nice how the children and parent view controllers are separated into different scenes.
If you want to achieve this effect in your own project, then there is a trick that is not perfect but very straightforward. In my example, suppose I have a container view controller that acts like a tab bar controller with only two tabs, 'left' and 'right'. I want to have a scene represent the parent view controller, and two separate scenes represent both the 'left' child view controller and the 'right' child view controller.
Even though it is impossible, it would be nice if I could create IBOutlets from the container view controller to its children in different scenes, and then when my container view controller is displayed set up the parent/child relationships according to the rules described the UIViewController documentation. If we had references to our 'left' and 'right' child view controllers, then we could set up the relationships no problem.
The standard solution to this referencing problem is to create references to child view controllers by dragging in Object outlets into the container view controller's scene, and then specifying their class type as being instances of the child view controller classes.
In order to keep children separated in different scenes like Apple's built-in containers, however, we will use a different trick. First, suppose we have the following properties declared in our container class, ContainerViewController:
#property (nonatomic, strong, readwrite) UIViewController *leftViewController;
#property (nonatomic, strong, readwrite) UIViewController *rightViewController;
In our storyboard, select the scene representing the 'left' view controller. In the attributes inspector, set the view controller's identifier property to "cvc_leftViewController" ("cvc_" refers to ContainerViewController, but really the identifier can be anything you want). Do the same for the right view controller's scene, setting it's identifier to "cvc_rightViewController".
Now insert the following code into ContainerViewController's viewDidLoad method:
if (self.storyboard) {
_leftViewController = [self.storyboard instantiateViewControllerWithIdentifier:#"cvc_leftViewController"];
_rightViewController = [self.storyboard instantiateViewControllerWithIdentifier:#"cvc_rightViewController"];
}
When ContainerViewController is loaded from the storyboard, it will go grab the 'left' and 'right' view controllers from their respective scenes and set references to them via its properties. Now that you have control of the child view controller instances, you can set up the parent/child relationships however you like. To learn how to do that properly refer to the UIViewController documentation.
This trick is not perfect, and has many caveats, but if you are careful you can make it work nicely for your project.
Edit: Although this is completely unnecessary and doesn't mean anything, if you really really want to have the storyboard display connections from your container to your child view controllers just like Apple's built-in containers, just use my method above and then set up segues directly between the container scene to the child scenes, and simply never perform those segues. Now everything will work correctly and look pretty too.
Can you associate child view controllers to a custom container view
controller in Storyboard?
I think what you're asking here is how to connect a view controller in one scene to an outlet of a view controller in a different scene. I don't believe that's possible, perhaps because the storyboard machinery may not have all the scenes in a storyboard loaded at the same time.
You're probably asking this because you want to pass some information from one view controller to another as you segue from one scene to the next. The way to do this when you're working with storyboards is to override -prepareForSegue:sender: in one or both view controllers affected by the segue. The UIStoryboardSegue object provided in the segue parameter has sourceViewController and destinationViewController properties, and also an identifier property. You can use these properties to identify the segue that's about to transfer data between the view controllers.
Ray Wenderlich's blog has a nice two-part tutorial on using storyboards that may help you:
Part 1 covers setting up a storyboard project, adding scenes, and creating segues.
Part 2 deals with using segues to transition between scenes, including the prepareForSeque method mentioned above.
iOS 5 allows multiple view controllers to be active in the same scene (although one should still be in charge), so a single scene in your storyboard might have several controllers. You can use outlets to connect these controllers to each other, and you can configure those connections the same way you did in IB: control-drag from one controller to another in the same scene. The usual outlet list will pop open to let you choose which outlet to connect.
The key to using multiple controllers in one scene (what I believe you are after here) is using the mysterious Object from the Objects list in IB to represent the other view controller and hooking up its outlets.
This answer How to create custom view controller container using storyboard in iOS 5 should help I hope. The answer also provides a working example app which is very helpful.
The problem with #Ben's (otherwise reasonable) answer is that it only works at one level of nesting. Beyond that, it would required that every subsequent VC is customized to save the nesting view controller in prepareForSegue.
To solve this, I spent too much time exploring an NSObject based index that that you could add to the Storyboard, bind to a scene, and which would then register it's parent VC in a global index, based on type and restorationId. That works / can work, but is too much effort in the end, and still requires the two step process of visually binding, and programmatically looking up.
For me, the simplest and most general solution is to lazily descend the view controller hierarchy
In my simple test project, I added the following lines to viewDidLoad:
self.left.data = [
"Zombie ipsum reversus ab viral inferno, nam rick grimes malum cerebro.",
"De carne lumbering animata corpora quaeritis." ]
where left is defined as:
lazy var left:CollectionViewController = { [unowned self] in
return self.childViewControllerWithId("Left") as! CollectionViewController }()
and childViewControllerWithId is defined as:
extension UIViewController {
func childViewControllerWithId(rid:String) -> UIViewController? {
// check immediate child controllers
for vc in self.childViewControllers as! [UIViewController] {
if vc.restorationIdentifier == rid { return vc }
}
// check nested controllers
for vc in self.childViewControllers as! [UIViewController] {
if let vc = vc.childViewControllerWithId(rid) {
return vc
}
}
assert(false, "check your assumptions")
return nil
}
}
Note that you could do other find variants based on type, if need be. Also note that the above requires that you define the restoration id in the Storyboard file. If you did not have repeated instances of the same view controller, then using type would be easier.
And to state what is hopefully obvious, you don't need to implement prepareForSegue, nor do you have to use the lazy loading, you just have to call find(...).

An UIViewController inside other UIviewController and IBActions

I'm designing an iPad app where little UIScrollViews have their own UIViewController . Those controllers have in their view a button that call an IBAction method. But it isnt working, in fact, it doesnt seem that they are being pressed in the simulator.
Here is some code to give you an idea of what im am doing .
// In UIViewController A (say the parent or root that have several UIScrollViews)
MiniViewController * mini = [[MiniViewController alloc]init];
[scrollView1 addSubview:mini.view];
//repeat the same process a couple of times with different uiscrollsviews and instances of miniviewcontrollers
Now The MiniController is very simple as you can guess, i only post the .h file
#interface MiniControlador : UIViewController {
IBOutlet UIButton * button;
}
#property (nonatomic, retain) IBOutlet UIButton * button;
- (IBAction)doSomething:(id)sender;
#end
You can see that i used Interface builder to connect an UIButton "button" to a method called doSomething. But as i already said, it isnt working.
One more thing. I also tried to add a button to the UIScrollView with the Mini Controller instance programmatically.And it worked! But I certainly believe that it's extremely hardcoded.
What do you think? I'll appreciate any suggestion(s).
Apple's View Controller Programming Guide is an important read, and explains a lot about Apple's philosophy of one-view-controller-per-screen.
Much of the behavior of view controllers is built on the assumption that there is only one view controller operating at a time. When that assumption is violated, the behavior is undefined (or at least undocumented). In this case, your description suggests that the normal view controller behavior of inserting the controller into the responder chain between its root view and that root's superview (usually the previous screen) isn't working.
While you may find methods of initialization that do work properly, they're not going to be guaranteed to work, and the behavior is liable to change with future OS updates.
Edit: A relevant quotes from the View Controller Programming Guide:
Each custom view controller object you create is responsible for managing all of the views in a single view hierarchy. In iPhone applications, the views in a view hierarchy traditionally cover the entire screen, but in iPad applications they may cover only a portion of the screen. The one-to-one correspondence between a view controller and the views in its view hierarchy is the key design consideration. You should not use multiple custom view controllers to manage different portions of the same view hierarchy. Similarly, you should not use a single custom view controller object to manage multiple screens worth of content.
Thanks guys, I finally solve this using objects of a class (that I called GenericViewController). It actually acts like a regular UIViewController, the IBActions responds well to any event (i.e. buttons being pressed).
I used an IBOutlet UIView in order to contain UILabels, buttons...and so on.
Here is some code if anyone is interested.
#interface GenericViewController : NSObject {
/* Some IBOutlets here*/
//like a regular UIView of an UIViewController, this holds the rest of the outlets
IBOutlet UIView * view;
}
//some IBActions here
}
Then the UIScrollView only add the view of each GenericViewController object
[scrollView addSubview:genericViewControllerObject.view];
If anyone has a better solution, please let me know :)
Are you sure you are loading the view from the xib you made in InterfaceBuilder?
I'm doing something similar in my app, and it's working for me.
I'm implementing the init method like this:
- (id)init
{
if (self = [super initWithNibName:#"__your_xib_name__" bundle:[NSBundle mainBundle]])
{
// TODO: Add additional initializing here
// ...
}
return self;
}
If you are not loading the view from the xib, then there will be no connections made (no IBOutlets initialized and no IBActions triggered).

Resources