Mastering SwiftUI: Building Beautiful and Interactive User Interfaces: Part 1

Modabbir Tarique
7 min readMay 30, 2023

--

Setting the Foundation

Welcome to a world where creativity knows no bounds, and the future of user interface development is at your fingertips. Get ready for an interesting voyage with SwiftUI, whether you’re a seasoned developer or just getting started. The way we create user interfaces has been completely transformed by Apple’s ground-breaking framework, which is now simpler, quicker, and more pleasurable than ever. Grab a keyboard, let your creativity run wild 😀, and let’s explore the fascinating world of SwiftUI!

With so many exciting concepts and techniques to cover, we’ve decided to embark on a journey that spans multiple blog posts. In this series, we’ll take a step-by-step approach, gradually building upon our knowledge to help you become a SwiftUI pro 😁.

The only pre-requisite for this series is you should have Xcode downloaded on your mac. If you don’t have Xcode, then you can download it from here.

In todays Blog we will discuss on the following points:

  1. What is SwiftUI?
  2. Advantages of SwiftUI over traditional user interface development frameworks
  3. Setting up SwiftUI project in Xcode
  4. SwiftUI View life cycle
  5. Understanding the basics of SwiftUI syntax

What is SwiftUI?

So, I assume after checking the title the first question that comes to your mind is what is SwiftUI?

SwiftUI is a modern framework developed by Apple for building user interfaces across various Apple platforms, including iOS, macOS, watchOS, and tvOS. It provides a declarative approach to UI development, allowing developers to describe the desired user interface and behaviour using simple and expressive Swift code.

And, you know the best part of using SwiftUI is compared to conventional UI frameworks like UIKit, SwiftUI allows developers to create aesthetically pleasing, responsive, and interactive interfaces with less code and in a more natural way. It embraces the idea of “declarative syntax,” where you specify the UI’s appearance and behaviour, and SwiftUI handles the implementation at the core.

Advantages of SwiftUI over traditional user interface development frameworks

SwiftUI offers several advantages over traditional user interface development frameworks like UIKit. Here, lets see some of the key advantages of SwiftUI:

  1. Declarative Syntax: This means you just need to describe what do you want as your desired outcome and let the framework handle the implementation. So, through this approach the code will be more readable and maintainable as here the main focus is on what we want to achieve rather then how to achieve.
  2. Cross-Platform Compatibility: With this now we can build user interfaces for multiple Apple platforms, using the same codebase. This can not only reduces the time of development but also the effort by enabling code reuse across different platforms.
  3. Live Preview and Real-Time Editing: We can live preview feature in Xcode, here allowing developers to see the changes they make to the user interface in real time. This can speeds up the development process and makes it easier to iterate and refine the UI.
  4. Automatic Layout and Responsiveness: SwiftUI’s layout system dynamically adjusts the location and size of views to fit various screen sizes and orientations. It is simpler to design interfaces that function well on a variety of devices, such as iPhones, iPads, and Macs.
  5. Seamless Integration with Swift: We can make use of Swift’s capabilities, such as safety, optionals, generics, and closures, to create spick and span code for our user interface in SwiftUI.
  6. State Management and Data Binding: SwiftUI introduces a robust data flow and state management model. It creates a link between the user interface and underlying data using the idea of bindings. This enables automatic updates and synchronization, ensuring that the UI always reflects the latest data changes.
  7. Easy Animation and Effects: With SwiftUI’s integrated animation framework, adding animations and visual effects to your user interface is simple. You can design interesting and interactive experiences for your app’s users with just a few lines of code.
  8. Accessibility by Design: In SwiftUI we have accessibility modifiers and features, making it easier to create apps that are inclusive and usable for all users, including those with visual or motor impairments.
  9. Backward Compatibility: While SwiftUI is a relatively new framework, Apple ensures backward compatibility by allowing SwiftUI and UIKit/AppKit to coexist. This means you can gradually adopt SwiftUI in your existing projects and leverage its advantages without rewriting your entire codebase.
  10. Rapid Development: SwiftUI makes development easier by cutting down on boilerplate code and offering strong built-in components. With its vast selection of pre-made views and controls, developers can quickly and efficiently design complicated interfaces with less code.

In short we can say that, SwiftUI empowers programmers with a cutting-edge and simple framework for creating beautiful, responsive, and cross-platform user interfaces while enhancing productivity and ensuring code maintainability.

Setting up SwiftUI project in Xcode

Lets, quickly learn how to setup a swiftUI project.

When you open Xcode, you can see the option of create a new Xcode project click on that.

Now, you will see multiple options but we want to create app. So, we’ll choose the App option.

Now, write the name of your App/product and in interface section use SwiftUI option.

After filling the Product Name and setting up the interface click on Next, now you will get then option where you want to save that project select the folder and click on create. Yes, you guess right thats it we have successfully setup our first SwiftUI project cheers! 😇

SwiftUI View life cycle

Each view in SwiftUI has a lifecycle that we can observe and manipulate during its three main phases. The three phases are Appearing, Updating, and Disappearing.

Apart from the three lifecycle phases, there are two rendering phases: Layout and Commit.

In the Layout phase, SwiftUI initialises the non-rendering view hierarchy, computes frames, connects views to state, calculates diffs to be committed onscreen.

NOTE: The layout phase must be pure. Any side effects will result in undefined behaviour.

Appearing: In this phase, a view is initialised, subscribed to the state, and rendered for the first time.

onAppear()

Updating: It is performed in response to an external event or state mutation.

Disappearing: Here, we remove view from the hierarchy.

onDisappear()

Understanding the basics of SwiftUI syntax

View Declaration:
Lets start with view Declaration, SwiftUI views are declared as structs that conform to the View protocol.

struct ContentView: View {
var body: some View {
// View content goes here
}
}

View Composition:

It is very easy to combine smaller views to create complex interfaces.

struct ContentView: View {
var body: some View {
VStack {
Text("Hello World")
.font(.title)
.foregroundColor(.blue)
Button("Tap On") {
// Button action
}
.padding()
.background(Color.green)
.foregroundColor(.white)
.cornerRadius(10)
}
}
}

Previewing the View:

SwiftUI also provide PreviewProvider . To preview a View add a PreviewProvider struct that returns an instance of the view.

struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}

Data and State Management:

SwiftUI provides various property wrappers to handle data and state changes within views.

@State is used to create mutable state properties that trigger view updates when changed.

@Binding is used to establish a two-way connection between a property in a parent view and a child view.

@ObservedObject is used for observing changes to an external object, typically conforming to the ObservableObject protocol.

struct ContentView: View {
@State private var count = 0

var body: some View {
VStack {
Text("Count: \(count)")
Button("Increment") {
count += 1
}
}
}
}

These are just a few basic concepts of SwiftUI syntax to give you a starting point. Absolutely! In the upcoming parts of our SwiftUI series, we will delve into view modifiers in more detail. We’ll explore various modifiers and their capabilities, demonstrating how they can be used to customize and enhance the appearance and behaviour of SwiftUI views.

Stay tuned for the upcoming parts of this series, where we’ll provide comprehensive explanations, practical examples, and hands-on exercises to help you master the art of using view modifiers effectively in SwiftUI. Get ready to take your UI customisation skills to the next level!

Check out the next part of the series: SwiftUI — Part2

Feel free to connect me on LinkedIn

Thanks for reading!

--

--

Modabbir Tarique

Full time Software Developer | IIT Guwahati Graduate | Tech Enthusiast