davidgagne.net

  • About
  • Archives
  • Twitter
  • Facebook
  • bartender.live
  • GitHub
  • LinkedIn

How to Add a UISwitch to a UINavigationBar

December 10th, 2017 @ 7:44 am PST

Quickly toggle state from the iOS navigation bar

How to Add a UISwitch to a UINavigationBar

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.

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!" )
    }
}

More posts tagged:
Apple / development / Programming / swift / xcode

More posts categorized:
Programming

More posts from:
December 2017 / 2017

Post navigation

Previous Post
Previous Post #FridayFive: Vacations
Next Post
Next Post Christmas Presents for Kids

Search


The Best T-Shirts (and Hats)

The Best T-Shirts (and Hats)

I cannot tell you how much I love 47 Brand Scrum t-shirts. They're crazy soft and comfortable, and available for all your favorite teams.

  • Take a Look

© David Vincent Gagne. All rights reserved. Custom WordPress Theme by Jacket Industries.