Search code examples
iosobjective-cuinavigationcontrolleruinavigationitem

How to make navigation bar's sub view pushed with view


I have a UISegmentedController on my navigationBar. The segmented control was added using below code:

@property (nonatomic) UISegmentedControl *segView;
...
- (void)viewDidLoad {
    [super viewDidLoad];

    _segView = [[UISegmentedControl alloc] initWithItems:@[@"Seg1", @"Seg2"]];
    [_segView setSelectedSegmentIndex:0];
    [_segView addTarget:self action:@selector(segmentAction:) forControlEvents:UIControlEventValueChanged];
    [self.navigationController.navigationBar addSubview:_segView];
}

When I push a view into navigationController, the segmented control is still there, so the recently pushed view's title will be overlapped with the segmented control.

enter image description here

How to make the segmented control to be pushed into the stack with the previous view?


Solution

  • Instead of adding UISegmentedControl as subView in navigationBar set as titleView of navigationItem like this.

    self.navigationItem.titleView = _segView;