So here is the problem I am trying to solve.
In each
viewController
I am trying to insert ads and the actual control elements. I finished couple of tutorial on raywenderlinch.com to understand that how people professionally put ads in their app. They used UIViews to have two views under mainview of view controller. So I completely understood that onesubview
hold the ads and another is holding actual app contents. if Ad is loaded take up the screen or else let other view have all available area.
After I came back to xcode I started coding the way I learned there. but when I was dropping UIView
on storyboard, I saw containerView
, which I think was not present when the tutorial was written.
So I am here to ask about the both approach and their pros and cons.
So basically its UIView
vs ContainerView
. Which way I should do, and why ?
Any help would be greatly appreciated.
If you see in detail these container view of UIView class type. To get the insights of why we need containerView you should see below portion
for more detail about container view goto link But before you begin you should have an understanding of
and also you can check this tutorial for how to use container view.
Thus you can go for both the approaches. Hope this will help you. happy coding :)
You use
UIView
when you already have a view and you do not need to have a dedicated view controller to build and handle interactions within it.From the UIView help page:
Simplified structure: YourViewController ---(has)---> UIView
You use
UIContainerView
when you need to embed another view controller in the one that you already have. The embedded view controller is in charge of returning a view for the region that theUIViewContainer
occupies. Therefore, yourUIContainerView
knows which view controller to use to renderUIView
inside the region it occupies.From the UIContainerView help page:
Simplified structure: YourViewController ---(has)---> SubViewController ---(has)---> UIView
That SubViewController returns a view and handles its events.
As an alternative answer, you can also consider the use case instead of the technical differences. For example: Why use a container view?
A common use for container views is to reuse (share) a view, directly in the storyboard. Previously, reusing a view required creating a separate "xib" file, and programmatically adding that view when the view controller was loaded.
The above image is from this extremely simple, easy to follow guide that walks you through how to setup a container view that is shared between 2+ view controllers.
A few other thoughts on when to use it:
Hopefully this helps people who are trying to figure out when a container view applies to them. If you have other example use cases, please edit/add them or leave them in the comments!