Self-learning Swift (4): Extracting View
When I was learning React, one important skill was learning how to create reusable components. This helped me manage my code better and made my projects easier to handle.
In Swift, the concept is similar but it's called extracting a view.
Creating a view of showing a player's score:
struct ScoreView: View {
var playerName: String
var score: Int
var body: some View {
HStack {
Text(playerName + ":")
.font(.headline)
.fontWeight(.bold)
Text("\(score)")
.font(.title)
}
.padding()
.background(Color.gray.opacity(0.2))
.cornerRadius(10)
}
}
And then reuse this view for different players:
struct ContentView: View {
var body: some View {
VStack {
ScoreView(playerName: "Alice", score: 1200)
ScoreView(playerName: "Bob", score: 900)
}
.padding()
}
}