How to add a segmented control to a navigation bar ? (iOS)
Asked Answered
V

3

8

I would like to add a segmented control to a navigation bar like this enter image description here

but when i drag the segmented control to the navigation bar the large title is gone. How can create the above UI ?

Volturno answered 10/4, 2018 at 2:32 Comment(0)
E
12

You should add the segmented control as the titleView of the navigation bar. Below is the sample code:

let titles = ["All", "Missed"]
segmentControl = UISegmentedControl(items: titles)
segmentControl.tintColor = UIColor.white
segmentControl.backgroundColor = UIColor.blue
segmentControl.selectedSegmentIndex = 0
for index in 0...titles.count-1 {
    segmentControl.setWidth(120, forSegmentAt: index)
}
segmentControl.sizeToFit()
segmentControl.addTarget(self, action: #selector(segmentChanged), for: .valueChanged)
segmentControl.selectedSegmentIndex = 0
segmentControl.sendActions(for: .valueChanged)
navigationItem.titleView = segmentControl
Epileptoid answered 10/4, 2018 at 4:12 Comment(1)
It works for me, thank you. Do you know a solution that doesn't requires to add the SegmentedControl programmatically?Amphipod
A
3

You can try the below simple code,

var segmentedController: UISegmentedControl!

let items = ["Label A", "Label B"]
segmentedController = UISegmentedControl(items: items)
navigationItem.titleView = segmentedController
navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Edit", style: .plain, target: self, action: #selector(handleSignOut))
navigationItem.rightBarButtonItem?.tintColor = UIColor.black
All answered 11/4, 2018 at 11:3 Comment(0)
M
2

If you want to add UISegmentControl by using XIB then you can do that by following these simple steps:

  1. Design your custom view in XIB (Refer XIB for your reference https://i.sstatic.net/AJDCo.png)
  2. Put the code in your ViewController

    class ViewController: UIViewController {
    
        lazy var navSegmentedView: YourCustomView = {
            guard let aView = Bundle.main.loadNibNamed("\(YourCustomView.self)", owner: self, options: nil)?.first as? YourCustomView else { return YourCustomView() }
    
            aView.backgroundColor = .clear
            aView.frame = CGRect(x: 0, y: 0, width: 160, height: 40)
            aView.segmentControl.addTarget(self, action: #selector(segmentChanged(_:)), for: .valueChanged)
    
            return aView
        }()
    
        override func viewDidLoad() {
            super.viewDidLoad()
            setupNavBar()
        }
    
        func setupNavBar() {
            navigationItem.titleView = navSegmentedView
            navigationItem.titleView?.backgroundColor = .clear
        }
    
        @objc func segmentChanged(_ sender: UISegmentedControl) {
            print(sender.selectedSegmentIndex)
        }
    
     }
    
Montanez answered 6/3, 2020 at 8:56 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.