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

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


Switch to FreshBooks

Switch to FreshBooks

I switched from QuickBooks to FreshBooks in 2015 and am so glad I did. Everything about their billing system is easier.

  • Take Control of Your Invoices

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