Quickly toggle state from the iOS navigation bar

How to Add a UISwitch to a UINavigationBar

UISwitchThere’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!" )
    }
}
Note: If you are a SwiftUI developer, you need to get Core Data Mastery from Big Mountain Studio. You'll learn everything you need to take your apps to the next level.

Post the first comment:

I'll never share your email address and it won't be published.

What Is This?

davidgagne.net is the personal weblog of me, David Vincent Gagne. I've been publishing here since 1999, which makes this one of the oldest continuously-updated websites on the Internet.

bartender.live

A few years ago I was trying to determine what cocktails I could make with the alcohol I had at home. I searched the App Store but couldn't find an app that would let me do that, so I built one.

Hemingway

You can read dozens of essays and articles and find hundreds of links to other sites with stories and information about Ernest Hemingway in The Hemingway Collection.