How to add UISegmentControl in UINavigationItem ..

2019-03-01 07:41发布

问题:

How do I add UISegmentedControl in UINavigationItem? I want to create a UINavigationBar with segment control which add in title of navigation bar.

UISegmentedControl has two indexes.

Here's what I have:

UISegmentedControl *segmentedControl = [[UISegmentedControl alloc] initWithItems:[NSArray arrayWithObjects:[UIImage imageNamed:@"grid.png"],[UIImage imageNamed:@"list.png"],nil]];
    [segmentedControl addTarget:self action:@selector(segmentedAction) forControlEvents:UIControlEventValueChanged];
    segmentedControl.frame = CGRectMake(0, 0, 90, 40);
    segmentedControl.segmentedControlStyle = UISegmentedControlStyleBar;
    segmentedControl.momentary = YES;
    [segmentedControl setTintColor:[UIColor clearColor]];

    UIBarButtonItem *segmentBarItem = [[UIBarButtonItem alloc] initWithCustomView:segmentedControl];    
    self.navigationItem.rightBarButtonItem = segmentBarItem;

I had put it in right side. So, also want to put in middle of navigation bar.

This does not work please let me know if I did anything wrong.

Thanks

回答1:

You're almost there, you just need to add the segmented control to a UINavigationItem and add that to your UINavigationBar:

// This code is used for a custom navigation bar

UINavigationItem* newItem = [[UINavigationItem alloc] initWithTitle:@""];
[newItem setTitleView:segmentedControl];

// Assuming you already have a navigation bar called "navigationBar"
[navigationBar setItems:[NSArray arrayWithObject:newItem] animated:NO];

// No memory leaks please...
[newItem release];

or if you want to use an existing controller

// This is used for an existing navigation controller
[navigationController.navigationBar.topItem setTitleView:segmentedControl];
// or if you want to access through the root view controller of the nav controller
[rootController.navigationItem setTitleView:segmentedControl];

That should set the center view of your navigation bar to the segmented control.

Hope I could help!

EDIT: If you need more help, the Apple documentation of these classes is quite thorough:

UINavigationItem

UINavigationBar