Reputation: 3083
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
Upvotes: 4
Views: 3436
Reputation: 124
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")
}
}
Upvotes: 7
Reputation: 1446
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 ..
}
}
Upvotes: 2
Reputation: 2702
Toggle UISwitch with more buttons as BarButtonItem in Swift 4
let switchControl = UISwitch(frame: CGRect(x:0, y:0, width:35, height:35))
switchControl.onTintColor = UIColor.red
switchControl.setOn(true, animated: false)
switchControl.addTarget(self, action: #selector(switchTapped(sender:)), for: .valueChanged)
let someImage = UIImage(named: "imageName")!
let someButton = UIBarButtonItem(image: someImage, style: .plain, target: self, action: #selector(someButtonTapped(sender:)))
self.navigationItem.rightBarButtonItems = [UIBarButtonItem.init(customView: switchControl),someButton]
Action
@objc func switchTapped(sender: UIBarButtonItem) {}
@objc func someButtonTapped(sender: UIBarButtonItem) {}
Upvotes: 0
Reputation: 3083
Getting closer .. but function is not being recognized ;[
@IBAction func togglePresence(sender: UIBarButtonItem) {
updateSwitch()
}
// hold empty status of switch
// this is set to true during viewDidLoad
var statusofswitch:Bool!
func updateSwitch() {
if statusofswitch == true {
statusofswitch = false
}
if statusofswitch == false {
statusofswitch = true
}
}
Upvotes: 0