如何在工具栏上添加分段控件,我正在添加但不是显示。 我的代码是:这些代码在viewDidload
上 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];
[self.navigationController.toolbar addSubview:segmentControll];
[self.view addSubview:toolBar];
答案 0 :(得分:7)
您只能将 UIBarButtonItem的添加到 UIToolbar 。
首先,将segmentControll添加到一个条形按钮项
UIBarButtonItem *segBarBtn;
segBarBtn = [[UIBarButtonItem alloc] initWithCustomView:segmentControl];
将栏按钮添加到工具栏
NSArray *toolbarItems = [NSArray arrayWithObject:segBarBtn];
[toolbar setItems:toolbarItems animated:NO];
答案 1 :(得分:1)
1。 self.navigationController.toolbar
与toolBar
不同。
2。你做错了。您应该将segmentControl
添加为UIBarButtonItem
:
UIBarButtonItem *btnItem = [[UIBarButtonItem alloc] initWithCustomView:segmentedControll];
toolBar.items = [NSArray arrayWithObject:btnItem];
答案 2 :(得分:0)
使用常规UIToolbar,可以通过将分段控件作为自定义UIBarButtonItem
的一部分来实现。
UIBarButtonItem * segmentBarItem = [[UIBarButtonItem alloc] initWithCustomView: segmentControll];
NSMutableArray *itemCopy = [self.toolbar.items mutableCopy];
[itemCopy addObject:segmentBarItem];
self.toolbar.items = itemCopy;
[itemCopy release];
[segmentBarItem release];
但是在你的情况下,你试图修改导航控制器的工具栏,这是不鼓励的。
此属性包含对由其管理的内置工具栏的引用 导航控制器。仅提供对此工具栏的访问权限 对于想要从工具栏显示操作表的客户。您 不应该直接修改UIToolbar对象。
您仍然需要创建自定义UIBarButtonItem,但您需要将其设置为rightBarButtonItem
答案 3 :(得分:0)
尝试这样的事情
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];