Leave a rating/review
Now that you have some experience with extracting views, it’s time to try this out on your own!
Your challenge is to extract three more views:
First, create a SliderLabelText View that will be used for the styled text views to the left and right of the slider.
Second, create a SliderView View that contains the HStack with the slider and its labels.
Third, create a HitMeButton View that contains the styled hit me button.
By the time you’re done, the body of your ContentView should look as simple as this.
That’s MUCH cleaner and easier to understand, isn’t it?
Allright - now pause the video and give this a shot. If you get stuck don’t worry, you can keep watching for the solution.
Add to TextViews.swift:
struct SliderLabelText: View {
var text: String
var body: some View {
Text(text)
.bold()
.foregroundColor(Color("TextColor"))
}
}
And to previews:
SliderLabelText(text: "99")
Modify ContentView.swift appropriately:
SliderLabelText(text: "1")
Slider(value: $sliderValue, in: 1.0...100.0)
SliderLabelText(text: "100")
Create SliderView:
struct SliderView: View {
@Binding var sliderValue: Double
var body: some View {
HStack {
SliderLabelText(text: "1")
Slider(value: $sliderValue, in: 1.0...100.0)
SliderLabelText(text: "100")
}.padding()
}
}
Modify ContentView.swift appropriately:
SliderView(sliderValue: $sliderValue)
Create HitMeButton:
struct HitMeButton: View {
@Binding var alertIsVisible: Bool
@Binding var sliderValue: Double
@Binding var game: Game
var body: some View {
Button(action: {
print("Hello, SwiftUI!")
alertIsVisible = true
}) {
Text("Hit me".uppercased())
.bold()
.padding(20.0)
.background(
ZStack {
Color("ButtonColor")
LinearGradient(gradient: Gradient(colors: [Color.white.opacity(0.3), Color.clear]), startPoint: .top, endPoint: .bottom)
})
.foregroundColor(Color.white)
.cornerRadius(21.0)
.font(.title3)
}
.alert(isPresented: $alertIsVisible) {
let roundedValue = Int(sliderValue.rounded())
return Alert(
title: Text("Hello there!"),
message: Text("The slider's value is \(roundedValue).\n" +
"You scored \(game.points( sliderValue: roundedValue)) points this round."),
dismissButton: .default(Text("Awesome!")))
}
}
}
Modify ContentView.swift appropriately:
HitMeButton(alertIsVisible: $alertIsVisible, sliderValue: $sliderValue, game: $game)