Mastering Swift UI- The Complete Guide (PART-3)

December 23, 2024

inspirethedev@gmail.com

Form Elements

Creating Forms with TextField, SecureField, and Pickers

import SwiftUI

struct ContentView: View {
    @State private var username: String = ""
    @State private var password: String = ""
    
    var body: some View {
        Form {
            Section(header: Text("Login Details")) {
                TextField("Enter your username", text: $username)
                    .textFieldStyle(RoundedBorderTextFieldStyle())
                
                SecureField("Enter your password", text: $password)
                    .textFieldStyle(RoundedBorderTextFieldStyle())
            }
            
            Button(action: {
                print("Username: \(username), Password: \(password)")
            }) {
                Text("Submit")
                    .frame(maxWidth: .infinity)
                    .padding()
                    .background(Color.blue)
                    .foregroundColor(.white)
                    .cornerRadius(8)
            }
        }
        .padding()
    }
}

Picker in a Form

struct ContentView: View {
    @State private var selectedOption = "Swift"
    let options = ["Swift", "Kotlin", "Java", "Python"]
    
    var body: some View {
        Form {
            Section(header: Text("Choose your favorite language")) {
                Picker("Select an option", selection: $selectedOption) {
                    ForEach(options, id: \.self) { option in
                        Text(option)
                    }
                }
                .pickerStyle(MenuPickerStyle()) // Dropdown-style picker
            }
            
            Text("You selected: \(selectedOption)")
                .font(.headline)
        }
    }
}

Styling Forms and Managing Input

struct ContentView: View {
    @State private var email = ""
    
    var body: some View {
        Form {
            Section(header: Text("User Info").font(.headline)) {
                TextField("Enter your email", text: $email)
                    .padding()
                    .background(Color.gray.opacity(0.2))
                    .cornerRadius(8)
                    .keyboardType(.emailAddress) // Keyboard type set karein
                    .autocapitalization(.none) // Automatic capitalization disable karein
            }
            
            Button(action: {
                print("Email entered: \(email)")
            }) {
                Text("Submit")
                    .font(.headline)
                    .frame(maxWidth: .infinity)
                    .padding()
                    .background(Color.green)
                    .foregroundColor(.white)
                    .cornerRadius(10)
            }
        }
        .padding()
    }
}

Styling UI with Shapes and Colors in SwiftUI

Adding Custom Shapes Using Circle, Rectangle, and Path

import SwiftUI

struct ContentView: View {
    var body: some View {
        VStack(spacing: 20) {
            Circle()
                .fill(Color.blue)
                .frame(width: 100, height: 100)
            
            Rectangle()
                .fill(Color.green)
                .frame(width: 120, height: 60)
            
            RoundedRectangle(cornerRadius: 20)
                .fill(Color.purple)
                .frame(width: 150, height: 80)
        }
    }
}
  • Circle(): Creates a circular shape.
  • Rectangle(): Creates a rectangular shape.
  • RoundedRectangle: Creates a rectangle with rounded corners.
  • .fill(Color): Used to fill the shape with a color.

Applying Gradients, Shadows, and Other Effects

import SwiftUI

struct ContentView: View {
    var body: some View {
        VStack(spacing: 20) {
            Circle()
                .fill(LinearGradient(gradient: Gradient(colors: [Color.red, Color.blue]), startPoint: .top, endPoint: .bottom))
                .frame(width: 100, height: 100)
            
            Rectangle()
                .fill(RadialGradient(gradient: Gradient(colors: [Color.green, Color.yellow]), center: .center, startRadius: 10, endRadius: 60))
                .frame(width: 120, height: 60)
            
            RoundedRectangle(cornerRadius: 20)
                .fill(AngularGradient(gradient: Gradient(colors: [Color.purple, Color.orange, Color.purple]), center: .center))
                .frame(width: 150, height: 80)
        }
    }
}

Combining Shapes and Effects

struct ContentView: View {
    var body: some View {
        ZStack {
            Circle()
                .fill(LinearGradient(gradient: Gradient(colors: [Color.pink, Color.purple]), startPoint: .top, endPoint: .bottom))
                .frame(width: 200, height: 200)
                .shadow(color: Color.purple.opacity(0.5), radius: 10, x: 0, y: 10)
            
            Text("SwiftUI")
                .font(.largeTitle)
                .fontWeight(.bold)
                .foregroundColor(.white)
        }
    }
}

Handling Navigation and Deep Link

Basic Navigation using NavigationView and NavigationLink:

import SwiftUI

struct ContentView: View {
    var body: some View {
        NavigationView {
            VStack {
                Text("Welcome to SwiftUI Navigation!")
                    .font(.largeTitle)
                    .padding()

                NavigationLink(destination: DetailView()) {
                    Text("Go to Details")
                        .font(.title)
                        .padding()
                        .background(Color.blue)
                        .foregroundColor(.white)
                        .cornerRadius(10)
                }
            }
            .navigationTitle("Home") // Title of this view
        }
    }
}

struct DetailView: View {
    var body: some View {
        VStack {
            Text("This is the Detail View!")
                .font(.title)
            Spacer()
        }
        .navigationTitle("Details") // Title of the next view
    }
}
struct ContentView: View {
    var body: some View {
        VStack(spacing: 30) {
            Text("User Profile")
                .font(.largeTitle)
                .fontWeight(.bold)
            
       
  • VStack: The main layout is vertical.
  • HStack: Profile picture and details are stacked horizontally.
  • ZStack: Text is placed on top of a rounded rectangle for button design.

Aligning and Customizing Stacks

struct ContentView: View {
    var body: some View {
        NavigationView {
            VStack {
                Text("Welcome to SwiftUI Navigation!")
                    .font(.largeTitle)
                    .padding()
            }
            .navigationTitle("Home")
            .navigationBarItems(trailing:
                Button(action: {
                    print("Settings tapped")
                }) {
                    Image(systemName: "gearshape")
                }
            )
        }
    }
}

Advanced Navigation: Using NavigationStack:

import SwiftUI

struct ContentView: View {
    var body: some View {
        NavigationStack {
            VStack {
                Text("Welcome to SwiftUI with NavigationStack!")
                    .font(.largeTitle)
                    .padding()

                NavigationLink("Go to Settings", value: "SettingsView")
            }
            .navigationDestination(for: String.self) { value in
                Text("This is \(value)!")
            }
            .navigationTitle("Home")
        }
    }
}

Passing Data Between Views:

struct ContentView: View {
    var body: some View {
        NavigationView {
            NavigationLink("Go to Details", destination: DetailView(message: "Hello from Home"))
                .padding()
        }
    }
}

struct DetailView: View {
    var message: String

    var body: some View {
        VStack {
            Text(message)
                .font(.title)
                .padding()
            Spacer()
        }
        .navigationTitle("Details")
    }
}

Customizing Navigation Bar with Large Titles and Back Button:

We can further customize the navigation bar in SwiftUI. We can set navigation bar right side up display mode and custom back buttons.

struct ContentView: View {
    var body: some View {
        NavigationView {
            NavigationLink("Go to Settings", destination: SettingsView())
                .padding()
        }
    }
}

struct SettingsView: View {
    var body: some View {
        VStack {
            Text("Settings Screen")
                .font(.title)
                .padding()
        }
        .navigationTitle("Settings")
        .navigationBarTitleDisplayMode(.large) // Large title
        .navigationBarBackButtonHidden(true) // Hide default back button
        .navigationBarItems(leading: Button(action: {
            print("Custom Back Button Tapped")
        }) {
            Image(systemName: "arrow.left")
        })
    }
}
  • navigationBarTitleDisplayMode(.large):This modifier is used to display a large title on the navigation bar.
  • navigationBarBackButtonHidden: This modifier allows you to hide the default back button from the navigation bar.
  • navigationBarItems(leading):This modifier allows you to add custom items (like a back button) to the navigation bar. The leading parameter places the item on the left side of the navigation bar.

Deep Linking in SwiftUI

import SwiftUI

@main
struct MyApp: App {
    @State private var deepLinkTarget: String? = nil // State to hold the deep link target
    
    var body: some Scene {
        WindowGroup {
            NavigationStack {
                ContentView(deepLinkTarget: $deepLinkTarget) // Pass deepLinkTarget to ContentView
            }
            .onOpenURL { url in
                // Deep linking logic to handle URL
                if url.path == "/detail" {
                    deepLinkTarget = "DetailView"
                }
            }
        }
    }
}

struct ContentView: View {
    @Binding var deepLinkTarget: String? // Binding to track deep link target
    
    var body: some View {
        NavigationStack {
            VStack {
                Text("Welcome to SwiftUI App!")
                    .font(.largeTitle)
                    .padding()
                
                if deepLinkTarget == "DetailView" {
                    // If deep link is pointing to DetailView, navigate programmatically
                    NavigationLink(destination: DetailView(), isActive: .constant(true)) {
                        EmptyView()
                    }
                }
            }
            .navigationTitle("Home")
        }
    }
}

struct DetailView: View {
    var body: some View {
        VStack {
            Text("This is the Detail View!")
                .font(.title)
            Spacer()
        }
        .navigationTitle("Details")
    }
}

Deep Linking with Dynamic Data:

import SwiftUI

@main
struct MyApp: App {
    @State private var itemId: String? = nil // State to hold dynamic item ID
    
    var body: some Scene {
        WindowGroup {
            NavigationStack {
                ContentView(itemId: $itemId) // Pass itemId to ContentView
            }
            .onOpenURL { url in
                // Handle deep link with dynamic data (e.g., item ID)
                if url.path == "/item" {
                    if let itemId = url.queryParameters?["id"] {
                        self.itemId = itemId
                    }
                }
            }
        }
    }
}

struct ContentView: View {
    @Binding var itemId: String? // Binding to hold item ID
    
    var body: some View {
        NavigationStack {
            VStack {
                Text("Welcome to the Item View!")
                    .font(.largeTitle)
                    .padding()
                
                if let itemId = itemId {
                    NavigationLink("Go to Item \(itemId)", destination: ItemDetailView(itemId: itemId))
                }
            }
            .navigationTitle("Home")
        }
    }
}

struct ItemDetailView: View {
    var itemId: String // Dynamic item ID
    
    var body: some View {
        VStack {
            Text("Item Details for ID: \(itemId)")
                .font(.title)
                .padding()
            Spacer()
        }
        .navigationTitle("Item Details")
    }
}

Comments

Leave a Reply

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