Challenge: Extract Views | raywenderlich.com


This is a companion discussion topic for the original entry at https://www.raywenderlich.com/18176818-your-first-ios-and-swiftui-app-polishing-the-app/lessons/7
1 Like

At the 3:05 mark, where Ray is just starting to scroll up, you can see the two Structs, InstructionsView and SliderView.

Why is it that in InstructionsView we reference the Binded variable “game” as just game on line 62, but for SliderView, we reference the Binded variable “sliderValue” as $sliderValue with a $(dollar sign)?

Good question! The difference is:

  • In InstructionsView you are accessing the target property (variable) on game. To access a property you don’t need the $.
  • In SliderView you are passing a reference to sliderValue to another view, as a binding. To pass a binding as a reference you need the $.

I hope that helps!

1 Like

It does help.

Thank you!

Doing the tutorial on Xcode 12.5.1 and I notice the blue background of the button peeking around the sides of the white border. Is there a way to fix that?

Screen Shot 2021-08-17 at 9.19.46 AM

struct HitMeButton: View {
  @Binding var alertIsVisible: Bool
  var sliderValue: Double
  var game: Game

I think property sliderValue and game in HitMeButton extract view is not attach @.Binding.
Because alertIsVisible property changed in Button but the other property is not.
Is it okay?

For the extracted HitMeButton, is it a good practice to have the alertIsVisible boolean as a state for the ContentView or would it make more sense to encapsulate this in the HitMeButton as its own state, since its managing the Alert? I did this rather than treating alertIsVisible as a Binding var.

struct HitMeButton: View {
	@State private var alertIsVisible: Bool = false
	@Binding var sliderValue: Double
	@Binding var game: Game

	var body: some View {
		Button(action: {
			alertIsVisible = true
		}) {
			Text("Hit me".uppercased())
				.bold()
				.font(.title3)
		}
		.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)
		.alert(isPresented: $alertIsVisible, content: {
			let roundedValue: Int = 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")))
	})
	}
}