Skip to main content

Change the Background (Guided Project Light)

Step Two: Change the Background

If the light is on—that is, if the background color is white—then tapping the button should turn off the light. Otherwise, if the light is off—meaning that the background is black—then tapping the button should turn on the light.

The statement "The light is on" is either a true or a false statement, so use a Boolean to determine how to change the background color.

1. Near the top of the ViewController class definition, create a variable named lightOn.

2. Set the initial value to true, because the screen initially has a white background.

var lightOn = true

Each time that the user taps the button, the value should change.     

3. Because the buttonPressed(_:) method executes when the user taps the button, make the change within this method:

@IBAction func buttonPressed(_ sender: UIButton) {
 lightOn = !lightOn
}

After the value changes, use the new value to determine the background color. If the value is true, change the background color to white. If the value is false, change the background color to black.

1. Write this logic using a simple if-statement:

@IBAction func buttonPressed(_ sender: UIButton) {
 lightOn = !lightOn
 if lightOn {
  view.backgroundColor = .white
 } else {
  view.backgroundColor = .black
 }
}    

2. Build and run your app.

The background color should successfully change on each tap of the button.

As your app continues to grow in size, you should keep your code well-organized. Rather than adding the if-statement directly inside the buttonPressed(_:) method, create a new method that updates the user interface(UI).

  1. Create a new method named updateUI().
  2. Move the if-statement from buttonPressed(:) to updateUI().
  3. Call the updateUI() method within buttonPressed(_:):
@IBAction func buttonPressed(_ sender: UIButton) {
 lightOn = !lightOn
 updateUI()
}
func updateUI() {
 if lightOn {
  view.backgroundColor = .white
} else {
  view.backgroundColor = .black
}
}

You reduce the risk of introducing bugs when you make small, incremental changes, as you did for this app. Using a single method that contains all the code that updates the view is a best practice for debugging interface issues.

Check the Solution if You Need It

Here is the entire Light project. You can compare it to how you coded the background. Review your methods and if-statements.

Teilen Sie Ihr Trailhead-Feedback über die Salesforce-Hilfe.

Wir würden uns sehr freuen, von Ihren Erfahrungen mit Trailhead zu hören: Sie können jetzt jederzeit über die Salesforce-Hilfe auf das neue Feedback-Formular zugreifen.

Weitere Infos Weiter zu "Feedback teilen"