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
Thanks for your query.
You can do this using the following steps.
In view did load, call setRightNavButton() and do the addition task as,
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")
}
}
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 ..
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With