How to add Xib to Storyboard
In the classic software project management book “The Mythical Man-Month: Essays on Software Engineering” published in 1975, Fred Brooks pointed out that regardless of the choice of programming language, a professional developer writes an average of 10 lines of code (LoC) per day.
Storyboards are beneficial for saving lines of code and improving efficiency. Apple strongly recommends them at every WWDC and continues to improve them over time.
I don’t understand why many team leaders still require their poor programmers to write UIViews programmatically.
Perhaps they believe that some CustomViews have strong reusability, and if they are pasted into a Storyboard, it would cause unnecessary side effects.
So, the main idea of this solution is to consolidate CustomViews into Xibs and then add them to a Storyboard.
This requires a few steps, because Apple does not directly support it.
- Add an
IBDesignable
CustomView.swift
andCustomView.xib
. - Set
CustomView.xib -> Placeholder -> File's Owner -> Custom Class
toCustomView
. - Programmatically create a new CustomView and load the root view from CustomView.xib.
- Add a root view with equal width and height in the horizontal and vertical center of the
CustomView
in the init function. - Now you can drag the view to the Storyboard and set its class to
CustomView
, which generates a snapshot for previewing.
However, the subviews of the CustomView (such as UIButton) cannot be connected to the ViewController’s @IBOutlet
.
This problem can be solved using Delegate
or Block
.
As for me, I recommend the Block
approach because I have used Delegate
for half a year and found that:
- The ViewController will have too many delegates.
delegate = self
must be written inviewDidLoad
, but sometimes= nil
inviewDidDisappear
.
The code for Block
will be shorter and simpler.
Here is an example that may save you some time.
Translated by gpt-3.5-turbo