How to easily create reusable xibs in XCode
A fully customizable way to create a reusable view to be used in multiple places
For views in the app, having a file that has the layout and another file that has the logic will save you a lot of time to manage them. If the design changes, only the xib will be modified, and if the logic changes, only the class file is changed. Here’s an image for the target folder structure:
I’ve created a repo that makes it very easy to create reusable view. Also, I added steps if you want to do a solution of your own.
Using MSAutoView
- Create a xib file and add the desired layout to it (Example):
2. Create a swift file and add a class that inherits from MSAutoView
3. In the storyboard, drag a normal UIView
to your view controller and set its class to the one created above (ListingView
)
4. Run the project, the view should contain the content of the xib
MSAutoView
has a lot of customization such as programmatically updating views, having multiple layouts for the same view, subclassing layouts and much more. You can find the project here:
Don’t forget to star the repo if you found it useful. Collaboration is highly appreciated.
Using a custom solution
- Create a xib file and add your custom layout in it:
- Create a class that inherits from
UIView
- Override
init(frame:)
andinit?(coder:)
functions to add a function which will contain adding the xib layout logic:
3. In the initView()
function, add this code:
Step 1: Since a xib can have multiple top level items which doesn’t have to be views (They can be objects, view controllers, etc..), we need to make sure that the first item is a UIView
Step 2: This is a very important step and most developers miss it (Including me). The iOS framework automatically adds constraints for views that have no constraints. So, if you try to add constraints without setting translatesAutoresizingMaskIntoConstraints
to false, you’ll have constraint conflicts and the view won’t be positioned properly.
Step 3: This step just creates an array of constraints on all sides with a constant of 0. There are a lot of libraries that can make this easier so you can use whatever you prefer.
Step 3: The view from the xib is added as a subview in the current view, and the constraints are added after that.
Note: The constraints are added to the parent view, not the subview.
4. This is the final implementation:
3. In the storyboard, add a normal view to your view controller and set its class to the one created (ListingView
)
4. Run the project, the view should contain the content of the xib
Thank you for checking this article out. Don’t forget to 👏 if you found it useful.