Create custom Template Xcode

Tram Ho

What is Xcode Templates?

XCode Templates is a tool to create files containing code to help optimize performance. In this tutorial, I will show you how to prepare a custom templates for the MVVM structure.

Often we need to create a structure and a file from scratch for a new module, and the process looks the same each time. For example – in the MVVM pattern, to create the Login module, we need to create directories at least the following 4 classes:

  1. LoginModule Folder
  2. LoginView
  3. LoginViewModel
  4. LoginViewController
  5. LoginModel

Adding each class and setting up code is time consuming. With the XCode template, we can speed up the process of adding them to the project.

I will show you how to configure templates to create them fastest with new MVVM module.

Install Xcode Templates

To install templates in XCode, we need to add a new directory containing custom templates.

Location of XCode iOS templates

All Xcode custom templates are located in ~ / Library / Developer / Xcode / Templates / and are grouped into sections by folder name. You can add it manually or using the terminal by running the following command:

mkdir ~ / Library / Developer / Xcode / Templates / Custom Templates

Template file structure

The main directory of the template

Each Template XCode file is a separate folder with the extension .xctemplate.

If you want to create a template named “View, Model & ViewModel”, you have to create a folder named “ View, Model & ViewModel.xctemplate ” in ~ / Library / Developer / Xcode / Templates / File Templates / Custom Templates .

Internal template and file folders

The TemplateInfo.plist file contains the basic template description. The implementation below gives us the ability to enter a Module name while creating XCode application templates.

You can use a text macro like FILEBASENAME to reference the filename.

Implement and structure

The directory structure of the template and Swift classes looks like this:

Step 1. Here’s how to implement the ViewController:

We have implemented the following:

  • Declare the variables viewModel and mainView. It will contain productName from TemplateInfo.plist.
  • Initialize variables
  • Required initialization (use ViewControllers from code, not Storyboards)
  • Implement viewDidLoad
  • The setupView function will add mainView and set SnapKit constraints

Step 2. Implement Model:

Model class name will be generated automatically by XCode so the above is just an example.

Step 3. Implement View:

Step 4. Implement ViewModel:


Click File -> New -> File…

Scroll down to the Template section:

Enter a name for the module:

Add it to the project:

You can completely customize the code for each file to suit your project, hope it is useful to you!

Share the news now

Source : Viblo