How to add segmented control on toolbar, I'm adding but not shows. my code is: these code is on viewDidload
toolBar = [[UIToolbar alloc]initWithFrame:CGRectMake(0.0, 325.0, 320.0, 44.0)];
toolBar.barStyle = UIBarStyleDefault;
NSAr开发者_如何学Cray *segmentItem = [[NSArray alloc]initWithObjects:@"Day",@"List",@"Month", nil];
UISegmentedControl *segmentControll = [[UISegmentedControl alloc]initWithItems:segmentItem];
segmentControll.frame = CGRectMake(80.0, 325.0, 200.0, 30.0);
//[self.toolBar addSubview:segmentControll];
[self.navigationController.toolbar addSubview:segmentControll];
[self.view addSubview:toolBar];
You can add only the UIBarButtonItem's to UIToolbar.
First, add the segmentControll to a bar button item,
UIBarButtonItem *segBarBtn;
segBarBtn = [[UIBarButtonItem alloc] initWithCustomView:segmentControl];
Add the bar button to the tool bar,
NSArray *toolbarItems = [NSArray arrayWithObject:segBarBtn];
[toolbar setItems:toolbarItems animated:NO];
1. self.navigationController.toolbar
is not the same as toolBar
.
2. You're doing it wrong. You should add segmentControl
as UIBarButtonItem
:
UIBarButtonItem *btnItem = [[UIBarButtonItem alloc] initWithCustomView:segmentedControll];
toolBar.items = [NSArray arrayWithObject:btnItem];
Try something like this
toolBar = [[UIToolbar alloc]initWithFrame:CGRectMake(0.0, 325.0, 320.0, 44.0)];
toolBar.barStyle = UIBarStyleDefault;
NSArray *segmentItem = [[NSArray alloc]initWithObjects:@"Day",@"List",@"Month", nil];
UISegmentedControl *segmentControll = [[UISegmentedControl alloc]initWithItems:segmentItem];
segmentControll.frame = CGRectMake(80.0, 325.0, 200.0, 30.0);
//[self.toolBar addSubview:segmentControll];
UIBarButtonItem *toolbarItem = [[[UIBarButtonItem alloc] initWithCustomView:segmentedControl] autorelease];
[toolBar addSubview:toolbarItem];
[self.view addSubview:toolBar];
With a regular UIToolbar you do so by making the segmented control a part of a custom UIBarButtonItem
like this.
UIBarButtonItem * segmentBarItem = [[UIBarButtonItem alloc] initWithCustomView: segmentControll];
NSMutableArray *itemCopy = [self.toolbar.items mutableCopy];
[itemCopy addObject:segmentBarItem];
self.toolbar.items = itemCopy;
[itemCopy release];
[segmentBarItem release];
But in your case you are trying to modify the toolbar of a navigation controller which is discouraged.
This property contains a reference to the built-in toolbar managed by the navigation controller. Access to this toolbar is provided solely for clients that want to present an action sheet from the toolbar. You should not modify the UIToolbar object directly.
You will still want to create a custom UIBarButtonItem but you will want to set it as the rightBarButtonItem
精彩评论