Introduction
The objective of this tip is to add an independent UIView
to storyboard. This is useful when we want to have an UIView
outside of the controller's view. Instead of creating a new .xib file and having a UIView
, we can use this approach to have the UIView
in storyboard itself. This approach is useful when we want to show and hide the UI widgets in controller's view.
Background
This tip assumes that you have sufficient knowledge of Xcode storyboard and Files owner in storyboard's View controller. For more information on storyboard, refer to this link.
Using the Code
Open storyboard and add a controller inside that as shown in Blank_storyboard
image screen.
Open UIObjects
library (shown in Storyboard_with-uiview
image screen) and pick any of the iOS widgets. Here, I picked UIView
from the library.
Now, select Files owner from the controller and drag and drop the picked UI widget next to Files owner. Now it looks as shown in Add_UIView_to_storyboard
image screen. By default, this newly dropped UI widget has its default dimensions, i.e., 170/120 approximately. You can change these dimensions according to your needs by selecting size inspector and change width and height values.
We can add as many UI widgets as we want in this newly added view. At the end, we should have IBOutlet
to this UI widget inside of the controller where we declare controller's IBOutlet
s (You can also sub
class this new UIView
if we want).
Note: Even though this newly dragged UI widget is added to the controller's files owner, it won't be part of your controller's view. We should explicitly add this dragged UI widget to controller's view whenever we want as shown below.
Assume that I have IBOutlet
name for dragged UIView
as customView
.
@property (nonatomic, weak) IBOutlet <code>UIView</code> * customView;
- (void)addCustomView {
[self.view addSubView:customView]; }
[<code>self</code>.customView setHidden:yes];
As mentioned in the above addCustomView
method, we can add custom view to controller's view.
Like this, we can add as many independent sub views we want in story board.
Points of Interest
One more thing to notice here is that, adding such kind of independent views in storyboard's view should be done only in case of when you want to swap between show and hide states of UI widget. This approach isn't applicable in case of UITableViewCell
.
To achieve the same using .xib, we have to create a new .xib file and then corresponding .h/.m source files. Then, we load this .xib file using loadNibNamed
method of NSBundle
class.
Summary
Adding a custom view in controller' view can be done by using storyboard itself rather than using .xib.