Search code examples
iosswiftuikituisegmentedcontroluinavigationitem

remove item from navigationItem to display navigationItems title programmatically


i have a UISegmentedControl in the Center of my NavigationItem. When a user with fewer rights logs into the app, the segmentedControl should be hidden, so instead of it the title of the navigationItem is shown.

I try to use .isHidden = true, but the title won't be shown.

What is a good way to achieve this? Of course, if you logout and login as an admin, you should see the segmentedControl again.


Solution

  • Assuming the UISegmentedControl is set via navItem.titleView...

    override func viewDidLoad() {
        title = "My Title"
        if userHasRights {
            let segmentedControl = UISegmentedControl()
            // Setup segmented control...
            navItem.titleView = segmentedControl
        }
    }
    

    Setting the .titleView on the navigation item should override the title set on the view controller.