Learn how to work with Xcode Previews in SwiftData App. SwiftData in combination with SwiftUI…
How to create Reusable Views in SwiftUI
![](https://appmakers.dev/wp-content/uploads/2024/01/reusable-views-swiftui-center-top-600x400.jpg)
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.