Search code examples
iosuisegmentedcontroluinavigationitem

iOS - NavigationItem titleView is centered on first load, but then becomes pinned to top left


I added a UISegmentedControl programmatically to navigationItem.titleView

The first time it is displayed it is centered like I would expect. But as soon as I dive down into a detail view controller, I can see my titleView's view pushed into the upper left corner, and nothing I've tried gets it back

In my initialization method I do this

UISegmentedControl *segmentedControl = [[UISegmentedControl alloc] initWithItems:segmentTextContent];
segmentedControl.selectedSegmentIndex = 0;
[segmentedControl setTranslatesAutoresizingMaskIntoConstraints:NO];
segmentedControl.autoresizingMask = UIViewAutoresizingFlexibleWidth;
//segmentedControl.frame = CGRectMake(0, 0, 280.0f, 30.0f);


self.navigationItem.titleView = segmentedControl;

I realized after a while that setting the CGRectMake has no affect

I've also tried putting this login in viewDidAppear but also did not change this outcome

Previously, when I tried putting a UISegmentedControl inside of another UIView, I lost the ability to click on the UISegmentedControl (I'm not sure if I had a variation of this which solved my positioning problems though)


Solution

  • If you only have 2 segments I don't think it's needed for the resizing, its width will always fit even for iPhone 4 and lower.

    What happens if you remove the following:

    [segmentedControl setTranslatesAutoresizingMaskIntoConstraints:NO];
    segmentedControl.autoresizingMask = UIViewAutoresizingFlexibleWidth;