Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Toggle UISwitch as BarButtonItem

Tags:

swift

I have a switch as a bar button but I am not sure how to reference the on/off value for a bar button item. XCode does not allow for the switch to be recognized as anything else except a bar button item. The switch is embedded in the barbutton and unable to be referenced.

@IBOutlet weak var toggleOutlet: UIBarButtonItem!
@IBAction func toggleButton(sender: UIBarButtonItem) {

   // if toggleOutlet.on // not recognized as bar button item

if anyone could help that would be great thanks

like image 335
Dazzle Avatar asked Oct 23 '25 04:10

Dazzle


2 Answers

Thanks for your query.

You can do this using the following steps.

In view did load, call setRightNavButton() and do the addition task as,


Updated to Swift 4.1 :

func audioSwitch(){
    let switchControl = UISwitch(frame: CGRect(origin: CGPoint(x: 0,y :0), size: CGSize(width: 50, height: 30)))
    switchControl.isOn = true
    switchControl.onTintColor = UIColor.white
    switchControl.setOn(true, animated: false)
    switchControl.addTarget(self, action: #selector(ViewController.switchValueDidChange(sender:)), for: .valueChanged)
    self.navigationItem.rightBarButtonItem = UIBarButtonItem.init(customView: switchControl)
}

@objc func switchValueDidChange(sender: UISwitch!)
{
    if sender.isOn {
        print("on")
    } else{
        print("off")
    }
}
like image 72
Md.Harish-Uz-Jaman Mridha Raju Avatar answered Oct 25 '25 23:10

Md.Harish-Uz-Jaman Mridha Raju


You can do this in Swift 4.1 like :

func rightNavButton(){

    let frameSize = CGRect(origin: CGPoint(x: 0,y :0), size: CGSize(width: 50, height: 30))
    let customSwitch = UISwitch(frame: frameSize)

    customSwitch.isOn = true
    customSwitch.onTintColor = UIColor.white
    customSwitch.setOn(true, animated: true)

    customSwitch.addTarget(self, action: #selector(ViewController.switchTarget(sender:)), for: .valueChanged)
    self.navigationItem.rightBarButtonItem = UIBarButtonItem.init(customView: customSwitch)
}


@objc func switchTarget(sender: UISwitch!)
{
    if sender.isOn {
        // do something ..
    } else{
        // do something ..
    }
}
like image 28
cs4alhaider Avatar answered Oct 26 '25 00:10

cs4alhaider



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!