-2

When I turn on the UISwitch I try to make it hide the background Image but I get the error: Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value. What am I doing wrong? when it was on the main storyboard it worked fine, but when on the settings storyboard it doesn't.

Code:

@IBAction func switchBackground(_ sender: UISwitch) {

    if (sender.isOn == true) {
    Background!.isHidden = false
    amountDue.textColor = UIColor.white
    amountMoney.textColor = UIColor.white
    amountPeople.textColor = UIColor.white
    }else {
    Background!.isHidden = true
    amountDue.textColor = UIColor.black
    amountMoney.textColor = UIColor.black
    amountPeople.textColor = UIColor.black
    amountDueText.textColor = UIColor.black
    amountPeopleText.textColor = UIColor.black
    amountMoneyText.textColor = UIColor.black

    }

}
Concon23b
  • 95
  • 1
  • 8

2 Answers2

0

Your problem is here

   Background!.isHidden = false

You can't change a property of an UIImageView that is currently not in an active view controller

You can use

   Background?.isHidden = false

but this will not achieve your goal if the imageView is nil

Shehata Gamal
  • 98,760
  • 8
  • 65
  • 87
0

Check that the @Outlet is connected for your background from storyboard. otherwise it will crash and thats what its telling you.

Also if background is @Outlet, you don’t need to force unwrap it with ! Unless you are initializing it programmatically and it’s a variable l, if so then make sure that the background is initialized for example: UIView()

One more note is to define the variable with small letter at the beginning to be background and not Background.

AaoIi
  • 8,288
  • 6
  • 45
  • 87