Some common views in SwiftUI

In the last article, we learnt the basics of SwiftUI – declarative programming, the SwiftUI View protocol, state variables and some understanding of how things work behind the scenes. Today, we’ll put these basics to practice and explore some quintessential and at times, sufficient, SwiftUI components for most user interfaces, namely:

  • Text
  • Image
  • TextField
  • Button
  • Stack Views – HStack,VStack and ZStack
  • List
  • ScrollView

We will dive right in, and begin with the humble ‘Text’ which is at the heart of most views.

Text

Text used to show any kind of static text with all the desired formatting. One can think of it as the EquivalenttoUIKit’s UILabel.

	Text("Hello World")

The code above would display a string “Hi” in black color as seen here:

Now, to add a bit of flavor, we can write

Text("Hello World")
          .foregroundColor(Color.red)

By simply adding a bit of code we have changed our text’s color to red. The foregroundColor method falls into the category of view modifiers which basically create a whole new view by applying modifications. As we have previously discussed, analogies to UIKit end just as soon as they start. Unlike UIKit, modifying properties will return a completely different view and not just assign values to an existing view. Why? Because we are no longer working with UIKit classes but with structures. 
There are few common view modifiers which we can use, like

  • background – to set background view/color 
  • padding – to set padding around the current view 
  • frame – to set width,height and positioning of a view
  • cornerRadius – to set corner radius for their edges
  • onTapGesture – to add a tap gesture and invocation when user taps on it

What’s more, we can create our own modifiers based on our preference and use them, but that is beyond the scope of this article.

Image (equivalent to UIKit’s UIImageView)

Image, as you can guess, is used to display an image. There are multiple ways to initialize an Image, depending on the type of image. For example, it can show SF Symbol Images and Asset library images as shown below: (SF Symbol Images are Apple’s default vector images which can be used in various fonts and colors. To know more about it please read from here.)

Image("logo")

	Image(systemName: "star.fill")

We can use all the view modifiers which we discussed on Text for Image too. In addition, the most commonly used view modifiers for Image are – 

  • resizable – By default, Image will take its frame size based on the actual image loaded into it regardless of what frame we have assigned, so in order to make it render in the frame we have to specify this. 
  • scaledToFill/scaledToFit – As name implies we are instructing swift UI to fill/fit our image onto the given frame.

TextField (equivalent to UIKit’s UITextField)

TextField used to get textual input from the user. It can be used as such

TextField(placeholderText, text: $value)

As you can see, in order to initialize the textfield we need to pass two parameters.

  • Placeholder Text – A string value which needs to be shown when there is no value for the text field – for informing the user what exactly we needed in this textfield
  • $value – Binding<String> – two-way binding string.

What is two-way binding? Let us understand it through an example.

According to Apple, a binding is used to create a two-way connection between a property that stores data, and a view that displays and changes the data. In the code shown above, the text in TextField will change automatically when textToDisplay changes in the parent ContentView. Likewise, whenever a user inputs something into the TextField, textToDisplay will also change.

Button (equivalent to UIKit’s UIButton)

A button can be simply initialized using

 Button(action: {
            //any action need to perform
        }, label: {
            Text("SIGN IN")
            }.frame(maxWidth: 300)
        })

Two parameters are needed for initializing the button.

  • action – a method where we can define what happens when the user presses on it.
  • label – a view that needs to be displayed on the button. It does not have to be Text always as we can return any view here which can be displayed as a button to the user.

Stack Views – HStack,VStack and ZStack (equivalent to UIKit’s UIStackView)

All the views we have discussed till now are standalone views and we need something to group them together. That’s where stack views come in. There are three different stack views as mentioned above

  • HStack – Places all its child views in horizontal order
  • VStack – Places all its child views in vertical order
  • ZStack – Placed all its child views one above another on the z-axis
HStack(alignment : .top,spacing: 10) {
      Spacer()
      Text("SIGN IN")
      Spacer()
      Text("SIGN UP")
      Spacer()
}

All stack views will have almost the same constructor pattern, the only difference would be the alignment. Where HStack follows vertical alignment, VStack has horizontal alignment and ZStack doesn’t have any alignment.
The constructor parameters:

  • alignment – decides how the child views need to be aligned inside the stack view
  • spacing – spacing between each child view
  • content – all the child views

Notice the neat little Spacer that we have used here. Spacer is a special view commonly used to add some space around the child views.

List (equivalent to UIKit’s UITableView)

List is used to show a list of items that are scrollable if content exceeds the given frame. 

List(contents) { contact in 
     Text(contact.name)
}

Parameters for initializing List:

  • Array of models which need to iterate upon. Note that the contents of the array conform to the protocol Identifiable
  • The method (closure) which operates upon the collection and returns a view

ScrollView (equivalent to UIKit’s UIScrollView)

ScrollView is used to make content scrollable when the containing view’s frame size is less than its content size.

 ScrollView(.vertical) {
    VStack {
        Text("Hi")
           .frame(height : 1000)
     }
}

Parameters for initializing the ScrollView 

  • Scroll direction – whether we need to vertical or horizontal scrolling
  • Method to render the content 

In conclusion

We are now familiar with some of the basic UI components of SwiftUI. These elements are flexible enough to be arranged into desired layouts and will suffice in most of the cases. Still, we have barely scratched the surface of the exciting and fresh ecosystem of SwiftUI. Let the exploration begin!

Leave a Reply