Guillem Perez
Guillem Perez

Reputation: 45

If statements with UISwitch state in Swift

I was wondering how I can I write an if statement for the state of a switch. I've tried with this:

if switch1 == true{
   label.text = "Light gray"
   scrollView.backgroundColor = UIColor.lightGrayColor()
}

Before that I created this outlets:

@IBOutlet weak var switch1: UISwitch!
@IBOutlet weak var scrollView: UIScrollView!
@IBOutlet weak var label: UILabel!

But this isn't working. How can I do this?

Upvotes: 0

Views: 726

Answers (2)

user8622187
user8622187

Reputation:

Swift 4 Solution:

The .on property has been renamed to .isOn, so your code should look somewhat like this:

if switch1.isOn {
    label.text = "Light gray"
    scrollView.backgroundColor = UIColor.lightGrayColor()
}

Upvotes: 0

Logan
Logan

Reputation: 53132

Use the .on property. You don't need to compare against true as well this way:

if switch1.on {
   label.text = "Light gray"
   scrollView.backgroundColor = UIColor.lightGrayColor()
}

Upvotes: 2

Related Questions