There’s a decent piece of sample code in the official Apple Developer Documentation labeled Customizing UINavigationBar’s appearance that explains how to add a few standard iOS control items. It does not tell you how to add a UISwitch to your UINavigationBar, though. There are plenty of StackOverflow questions related to the UISwitch control, but I couldn’t find any describing how to get it in the nav bar.
Add this to viewDidLoad()
anywhere after super.viewDidLoad()
:
let my_switch = UISwitch(frame: .zero) my_switch.isOn = true // or false my_switch.addTarget(self, action: #selector(switchToggled(_:)), for: .valueChanged) let switch_display = UIBarButtonItem(customView: my_switch) navigationItem.rightBarButtonItem = switch_display
As far as I know, the function called in the addTarget #selector can be pretty much anything you want. Here’s an example:
@IBAction func switchToggled(_ sender: UISwitch) { if sender.isOn { print( "The switch is now true!" ) } else{ print( "The switch is now false!" ) } }