In this article we will create a template that creates a view and a viewModel files.
In the previous article http://trikalabs.com/xcode-templates/ we explore how to create a simple file template.
Now let’s add a folder under the “Templates” folder and let’s name it SwiftUIMVVM.xctemplate.
Inside this folder we will need the TemplateInfo,plist file and a subfolder with our file templates.
Let’s create the TemplateInfo,plist (We can copy an existing one and modify it).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 |
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>Kind</key> <string>Xcode.IDEKit.TextSubstitutionFileTemplateKind</string> <key>Platforms</key> <array> <string>com.apple.platform.iphoneos</string> </array> <key>Options</key> <array> <dict> <key>Identifier</key> <string>productName</string> <key>Required</key> <true/> <key>Name</key> <string>Module Name:</string> <key>Description</key> <string>The name of the SwiftUI Module</string> <key>Type</key> <string>text</string> <key>Default</key> <string></string> </dict> <dict> <key>Identifier</key> <string>type</string> <key>Required</key> <true/> <key>Name</key> <string>Type:</string> <key>Description</key> <string>SwiftUIMVVM</string> <key>Type</key> <string>popup</string> <key>Default</key> <string>SwiftUI MVVM Template</string> <key>Values</key> <array> <string>MVVM Template</string> </array> </dict> </array> </dict> </plist> |
We created a module name input variable and the name of the folder which contains the file templates.
Now let’s create the two file templates:
And let’s edit the ViewModel first:
1 2 3 4 5 6 7 8 |
import Combine class ___FILEBASENAME___: ObservableObject { init() { } } |
And then the view
1 2 3 4 5 6 7 8 9 10 11 12 13 |
import SwiftUI struct ___FILEBASENAME___: View { @ObservedObject private var viewModel: ___FILEBASENAME___Model init(viewModel: ___FILEBASENAME___Model) { self.viewModel = viewModel } var body: some View { EmptyView() } } |
Now when create a new file in Xcode we can see the new option:
we can name it:
And we can see the new files
If we look on the View file for example we see that everything is being created as expected:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
import SwiftUI struct FeatureAView: View { @ObservedObject private var viewModel: FeatureAViewModel init(viewModel: FeatureAViewModel) { self.viewModel = viewModel } var body: some View { EmptyView() } } |