Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

} 
like image 271
user3708224 Avatar asked Jan 23 '26 09:01

user3708224


1 Answers

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
}
like image 160
Danh Huynh Avatar answered Jan 25 '26 08:01

Danh Huynh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!