4.1. Creating a separate View code file

Now let's create a separate file, 'FirstScreenView.swift' in the project.

  • Click File -> New -> File...

  • Select Cocoa Touch Class and press Next

  • The class name should be FirstScreenView.

  • Select UIView as for 'Subclass of.' And press Next.

  • Press Create.

Setting up the View

FirstScreenView will be our View (front end) code file. We will declare the UI elements in the file like the following:

Now, we will override the init() method to initialize the View. So let's write:

In the above code, we initialize the FirstScreenView with a rectangular frame. The frame comes from the view where we will patch this screen later.

Now, Xcode will yell at you saying, 'required' initializer 'init(coder:)' must be provided by the subclass of 'UIView'. UIView adopts the NSCoder protocol, so we must override the init() method with the coder parameter. Do not worry about it; just click on the red sign and click fix. That should automatically do the stuff for you. And you can keep the generated method untouched.

Let's start building the View now. We trivially add the following initializing methods like how we did before:

In the above code, notice that I am setting the 'backgroundColor' to white because it would, by default, populate a black screen without the background color. The init(frame: CGRect) method is used as the initializer of the instance of the FirstScreenView. If you look carefully at the setup methods, we are not saying view.addSubView() like before. This class is already a UIView, so we use self.addSubView() method.

Now let's initialize the constraints:

Notice that here to set up the constraints, I am using self instead of view for the same reason, this FirstScreenView is a UIView itself. I am adding children of the self view.

Last updated

Was this helpful?