Skip to content
👩🏻‍💻 🧑🏽‍💻 Join us for Free for Full Access to site Content

How to create Reusable Views in SwiftUI

Reusable views in SwiftUI are like your favorite set of Lego blocks – versatile, fun, and ready to be used in all sorts of creative ways.

Why Reusable Views?

  • Playful Creativity: Build once, use in many imaginative ways.
  • Aesthetic Consistency: Keep a uniform look with your own custom UI elements.
  • Easy Tweaks: Change in one place, see the magic happen everywhere.

Building a Custom Star Rating View

Let’s create something fun – a Star Rating view that can be used across your app:

import SwiftUI

struct StarRating: View {
    var rating: Int

    var body: some View {
        HStack {
            ForEach(1...5, id: \.self) { number in
                Image(systemName: number <= rating ? "star.fill" : "star")
                    .foregroundColor(number <= rating ? .yellow : .gray)
            }
        }
    }
}

With StarRating, you can display ratings in a fun and interactive way.

Implementing Star Rating

Time to sprinkle some stars in your app:

struct ContentView: View {
    var body: some View {
        VStack {
            Text("Rate our Adventure Game")
            StarRating(rating: 4)
            // More whimsical UI components...
        }
    }
}

A Reusable Animated Button

Let’s add more fun with an animated button:

struct AnimatedButton: View {
    var buttonText: String
    @State private var isPressed = false

    var body: some View {
        Button(action: {
            self.isPressed.toggle()
        }) {
            Text(buttonText)
                .padding()
                .background(isPressed ? Color.green : Color.blue)
                .foregroundColor(.white)
                .animation(.easeInOut)
                .cornerRadius(10)
        }
    }
}

The AnimatedButton changes color when pressed, adding an interactive touch to your UI.

Using Animated Button

Now, let’s put this playful button into action:

struct ContentView: View {
    var body: some View {
        VStack {
            AnimatedButton(buttonText: "Start Adventure")
            // Your fantastical SwiftUI journey continues...
        }
    }
}

Conclusion

Creating reusable views in SwiftUI is not just efficient, it’s a doorway to endless creativity. Embrace this opportunity to design unique and engaging UI components that bring your apps to life.

 

 

 

Back To Top
Search

Get Latest App Development News, Tips and Tutorials

* indicates required