How to add the UISegmentedControl in UINavigationBar?

Jacky Shek picture Jacky Shek · May 28, 2015 · Viewed 25.7k times · Source

I have tried to add the UISegmentedControl to the bottom of UINavigationBar with title. But i cannot add it and I cannot add UISegmentedControl in the tableView.headerView,because i need the search bar in the tableView.headerView, so there is just one solution that i need to add UISegmentedControl to the bottom of UINavigationBar. Anyone have another idea that i can solve this situation?

Here is the code that I have tried(with Swift):

        class searchingViewController: UITableViewController{ 
                override func viewDidLoad() {         
                    var items: [AnyObject] = ["Searching Method A", "Searching Method B"]
                    var searchSC:UISegmentedControl!
                    searchSC.frame = CGRectMake(0, 0, frame.width - 20, 30)
                    searchSC.selectedSegmentIndex = 1
                    searchSC.backgroundColor = UIColor(white: 1, alpha: 1)
                    searchSC.layer.cornerRadius = 5.0
                    navigateUIToolBar = UIToolbar(frame: CGRectMake(frame.minX + 10, ios7_8Info.getStatusBarHeight()+self.navigationController!.navigationBar.frame.height+frame.minY+(21/2),
                        frame.width - 20, 30))

                    navigateUIToolBar.addSubview(searchSC)
                    self.navigationController?.navigationBar.addSubview(navigateUIToolBar)
                  }
          }

Answer

Hardik Thakkar picture Hardik Thakkar · May 6, 2016

To add segment control in UINavigationBar in Swift 5

    let segment: UISegmentedControl = UISegmentedControl(items: ["First", "Second"])
    segment.sizeToFit()
    if #available(iOS 13.0, *) {
        segment.selectedSegmentTintColor = UIColor.red
    } else {
       segment.tintColor = UIColor.red
    }
    segment.selectedSegmentIndex = 0
    segment.setTitleTextAttributes([NSAttributedString.Key.font : UIFont(name: "ProximaNova-Light", size: 15)!], for: .normal)
    self.navigationItem.titleView = segment