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.

계속해서 무료로 학습하세요!
계속 진행하려면 계정을 가입하세요.
얻을 수 있는 이점
  • 커리어 목표에 대한 개인화된 권장 사항 제공받기
  • 실습 과제 및 퀴즈를 통해 스킬 연습
  • 진행 상황을 추적하고 고용주에게 공유
  • 멘토십과 커리어 기회에 연결