Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to link a boolean value to the on/off state of a UISwitch?

Tags:

ios

swift

I have a UISwitch that I want to control a boolean value in a function I wrote. I looked in the UISwitch Type Reference and it listed the property for the on/off state of the switch as on. I tried to use this in a action:

@IBAction func switchValueChanged(sender: UISwitch) {
        if acsessabilitySwitch.on {
//accessibilitySwitch is the UISwitch in question 
            println("It's True!")
            advice.isInProduction = Bool (true) 
// isInProduction is a attribute of a class
        } else {
            println("It's False!")
            advice.isInProduction = Bool (false)
        }

but when I ran it and hit the switch it crashed and didn't print anything.

EDIT: Here is my ViewController and my custom class files:

BuyingAdviceModel.swift:

import Foundation
class videoGameModel{
    var price : Double
    var isInProduction : Bool
    var adviceGiven: String?
    init (isInProduction : Bool, price: Double){
        self.price = price
        self.isInProduction = isInProduction
    }
    func giveAdvice (price:Double, isInProduction:Bool)->(adviceGiven:String){
            if price >= 199.99 {
                var adviceGiven = "Nope, that's too expensive!"
                return adviceGiven
            } else if price <= 99.99{
                if isInProduction == true {
                    var adviceGiven = ("Buy it at GameStop!")
                    return adviceGiven
                } else {
                    var adviceGiven = ("Go look online!")
                    return adviceGiven
                }
            } else {
                var adviceGiven = ("Are you sure you put the info in correctly?")
                return adviceGiven
            }
    }
}

ViewController.swift:

import UIKit
import Foundation
class ViewController: UIViewController {
    @IBOutlet var priceTextField: UITextField
    @IBAction func adviceButtonTapped(sender: AnyObject) {
        let adviceOutputed = advice.adviceGiven!
        adviceLabel.text=adviceOutputed
    }
    @IBAction func viewTapped(sender: AnyObject) {
        priceTextField.resignFirstResponder()
    }

     @IBOutlet var acsessabilitySwitch: UISwitch
     @IBOutlet var adviceLabel: UILabel
     @IBAction func switchValueChanged (sender: UISwitch) {
        advice.isInProduction = sender.on
        println ("It's " + advice.isInProduction.description + "!")
    }
    var advice = videoGameModel (isInProduction: true,price: 0.00)
    func refreshUI(){
        priceTextField.text = String(advice.price)
        adviceLabel.text = ""
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        refreshUI()
    }

    override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
    }


}
like image 760
user3832611 Avatar asked Jul 12 '14 16:07

user3832611


4 Answers

Add the UISwitch Reference into ViewController.swift file.

@IBOutlet var mySwitch: UISwitch 
@IBOutlet var switchState: UILabel

then add the target event into the viewdidload method like below

mySwitch.addTarget(self, action: #selector(ViewController.switchIsChanged(_:)), forControlEvents: UIControlEvents.ValueChanged)

When the switch is flipped the UIControlEventValueChanged event is triggered and the stateChanged method will be called.

func switchIsChanged(mySwitch: UISwitch) {
    if mySwitch.on {
        switchState.text = "UISwitch is ON"
    } else {
        switchState.text = "UISwitch is OFF"
    }
}

Swift 3.0

func switchIsChanged(mySwitch: UISwitch) {
    if mySwitch.isOn {
        switchState.text = "UISwitch is ON"
    } else {
        switchState.text = "UISwitch is OFF"
    }
}

Swift 4.0

@objc func switchIsChanged(mySwitch: UISwitch) {
    if mySwitch.isOn {
        switchState.text = "UISwitch is ON"
    } else {
        switchState.text = "UISwitch is OFF"
    }
}

find brief tutorial in https://sourcefreeze.com/uiswitch-tutorial-using-swift-in-ios8/

like image 132
Bharathi Devarasu Avatar answered Oct 30 '22 21:10

Bharathi Devarasu


Succinctness, even parsimony, is important in coding style. Try this:

@IBAction func switchValueChanged (sender: UISwitch) {
  advice.isInProduction = sender.on
  print ("It's \(advice.isInProduction)!")
}

In your original code, you likely crashed because acsessabilitySwitch or advice are unbound (have values of nil).

[Updated - replaced println with print]

like image 36
GoZoner Avatar answered Oct 30 '22 23:10

GoZoner


For swift 3

enter image description here

@IBAction func switchValueChanged(_ sender: UISwitch) {
        print(sender.isOn)
}
like image 7
Hamza Üzümcü Avatar answered Oct 30 '22 21:10

Hamza Üzümcü


Drag and drop UISwitch from Object Library-

@IBOutlet-

@IBOutlet weak var myswitch: UISwitch!

@IBAction-

@IBAction func onAllAccessory(sender: UISwitch) {

        if myswitch.on == true{
            onCall()
        }
        if myswitch.on == false{
            offCall()
        }
    }

Your function-

func onCall(){
        print("On is calling")
    }
    func offCall(){
        print("Off is calling")
    }
like image 4
Swift Developer Avatar answered Oct 30 '22 22:10

Swift Developer