SwiftUI – How to create a Form

By | 13/05/2020

In this post, we will see how to create a Form in Swift.

We start creating a file called PageForm.swift and then, we set it as starter page, changing the file SceneDelegate.swift:

import UIKit
import SwiftUI

class SceneDelegate: UIResponder, UIWindowSceneDelegate {

    var window: UIWindow?

    func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
        let contentView = PageForm()

        // Use a UIHostingController as window root view controller.
        if let windowScene = scene as? UIWindowScene {
            let window = UIWindow(windowScene: windowScene)


import SwiftUI

struct PageForm: View {
    // definition of variables
    @State private var email:String = ""
    @State private var password: String = ""
    @State private var firstName:String = ""
    @State private var lastName:String = ""
    @State private var showingSummary = false
    // definition of the "SendData" function, called 
    // when the button "Create" is pushed
    func SendData(){
        showingSummary = true

    // The form will be disabled until all fields are filled
    var disabledForm: Bool{
        firstName.isEmpty || lastName.isEmpty || email.isEmpty || password.isEmpty
    var body: some View {
        NavigationView {
            // Form definition
            Form {
                // Definition of User Info section
                Section(header: Text("User Info").fontWeight(.bold).font(.system(size: 18))) {
                    TextField("First Name", text: $firstName)
                    TextField("Last Name", text: $lastName)
                // Definition of Username & Password section
                Section(header: Text("Username & Password").fontWeight(.bold).font(.system(size: 18))) {
                    TextField("Email", text: $email)
                    SecureField("Password", text: $password)
                Section {
                    Button(action: SendData) {
                } // by default the section is disabled
            }.navigationBarTitle(Text("Create new User"))
             // The app will show an alert when the  Form is enabled, 
             // and the "Enter" button has been clicked
            .alert(isPresented: $showingSummary) {
                Alert(title: Text("Your Password is"), message: Text("\(password)"), dismissButton: .default(Text("OK")))

struct PageForm_Previews: PreviewProvider {
    static var previews: some View {

If we run the application, this will be the result:

Leave a Reply

Your email address will not be published. Required fields are marked *