Search code examples
iphoneobjective-cxcodecocoa-touchios6

Adding a segmented control to the center of UINavigationBar


I am trying to add a UISegmentedControl to the middle of a UINavigationBar of only one view (not the entire view controller). How can I go about doing this?

Other answers I read only allow an entire view controller to contain a UINavigationItem as the title. I need it to show only on one view.


Solution

  • This code will help you.

    UISegmentedControl *segmentedControl = [[UISegmentedControl alloc] initWithItems:
                                                [NSArray arrayWithObjects:@"Add",@"Delete",
                                                 nil]];
        segmentedControl.frame = CGRectMake(0, 0, 80, 30);
        segmentedControl.segmentedControlStyle = UISegmentedControlStyleBar;
        [segmentedControl setWidth:35.0 forSegmentAtIndex:0];
        [segmentedControl setWidth:45.0 forSegmentAtIndex:1];
    
        [segmentedControl addTarget:self action:@selector(segmentAction:) forControlEvents:UIControlEventValueChanged];
        segmentedControl.momentary = YES;
    
        UIBarButtonItem *segmentBarItem = [[UIBarButtonItem alloc] initWithCustomView:segmentedControl];
        [segmentedControl release];
    
        self.navigationItem.leftBarButtonItem = segmentBarItem;
        [segmentBarItem release];
    

    result of this code is

    enter image description here

    Edit:

    Exact code that would work:

    UISegmentedControl *segmentedControl = [[UISegmentedControl alloc] initWithItems:
                                                [NSArray arrayWithObjects:@"Add",@"Delete",
                                                 nil]];
        segmentedControl.frame = CGRectMake(0, 0, 80, 30);
        segmentedControl.segmentedControlStyle = UISegmentedControlStyleBar;
        [segmentedControl setWidth:35.0 forSegmentAtIndex:0];
        [segmentedControl setWidth:45.0 forSegmentAtIndex:1];
    
        [segmentedControl addTarget:self action:@selector(segmentAction:) forControlEvents:UIControlEventValueChanged];
        segmentedControl.momentary = YES;
    
        self.navigationItem.titleView = segmentedControl;