Search code examples
swiftxcodeuisegmentedcontrolprogrammatically-created

programmatically embedding segmented control inside navigation bar


I am trying to insert a segmented control inside a navigation bar programmatically and am having some trouble loading the segmented controller in the nav bar. I am sure this very simple, but see code below. Thanks in advance!

var segmentedController: UISegmentedControl!

override func viewDidLoad() {
    super.viewDidLoad()

    navigationItem.titleView = segmentedController
    let items = ["Label A", "Label B"]
    segmentedController = UISegmentedControl(items: items)

    navigationItem.leftBarButtonItem = UIBarButtonItem(title: "Sign Out", style: .plain, target: self, action: #selector(handleSignOut))
    navigationItem.leftBarButtonItem?.tintColor = UIColor.black

} 

Solution

  • You should add the segmentedController to the navigation bar after initializing it!

    var segmentedController: UISegmentedControl!
    
    override func viewDidLoad() {
        super.viewDidLoad()
    
        let items = ["Label A", "Label B"]
        segmentedController = UISegmentedControl(items: items)
        navigationItem.titleView = segmentedController
    
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "Sign Out", style: .plain, target: self, action: #selector(handleSignOut))
        navigationItem.leftBarButtonItem?.tintColor = UIColor.black
    }