SwiftUI Series 3: Creating a Dynamic Image Resizer with Binding

In this tutorial, we'll explore how to create a simple yet interactive SwiftUI app that allows users to dynamically resize an image using a slider. We'll cover concepts like @State, binding, and how to create a responsive UI.

The Goal

We're building an app with the following features:

  • Display a system image
  • Show the current size of the image
  • Provide a slider to adjust the image size in real-time

The Code

Let's start by looking at the complete ContentView struct:

import SwiftUI

struct ContentView: View {
    @State private var imageSize: CGFloat = 0

    var body: some View {
        VStack {
            Image(systemName: "figure.walk")
                .imageScale(.large)
                .foregroundStyle(.tint)
                .font(.system(size: imageSize))

            Text("The Image Above Size is : \(Int(imageSize))")

            Slider(value: $imageSize, in: 1...300, step: 10)
                .tint(.blue)
                .padding()
        }
        .padding()
    }
}

Breaking It Down

1. State Variable

@State private var imageSize: CGFloat = 0

We start by declaring a @State variable imageSize. This will store the current size of our image and automatically trigger UI updates when its value changes.

2. The Image

Image(systemName: "figure.walk")
    .imageScale(.large)
    .foregroundStyle(.tint)
    .font(.system(size: imageSize))

We're using a system image ("figure.walk") and setting its size dynamically using the imageSize state variable.

3. Size Display

Text("The Image Above Size is : \(Int(imageSize))")

This text view displays the current size of the image, converting the CGFloat to an Int for cleaner display.

4. The Slider

Slider(value: $imageSize, in: 1...300, step: 10)
    .tint(.blue)
    .padding()

Here's where the magic happens. We're using a Slider view, binding its value to our imageSize state variable. The $ symbol creates a two-way binding, allowing the slider to both read and write the imageSize value.

  • in: 1...300: This sets the range of the slider from 1 to 300.
  • step: 10: This makes the slider move in increments of 10.

How It Works

  1. When the app launches, the image is displayed at its default size.
  2. As the user moves the slider, the imageSize state variable updates.
  3. This triggers a redraw of the Image view with the new size.
  4. Simultaneously, the text updates to display the new size.

Conclusion

This simple example demonstrates the power of SwiftUI's declarative syntax and state management. With just a few lines of code, we've created an interactive UI that responds to user input in real-time.

Try expanding on this example by adding more customization options or applying the concept to other UI elements!