如何在UINavigationItem ..中添加UISegmentControl?

如何在UINavigationItem添加UISegmentedControl ? 我想创build一个带有段控件的UINavigationBar ,它添加了导航栏的标题。

UISegmentedControl有两个索引。

这是我有:

 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; 

我把它放在右侧。 所以,也要放在导航栏的中间。

如果我做错了,请告诉我。

谢谢

你几乎在那里,你只需要添加到UINavigationItem分割控制,并将其添加到您的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]; 

或者如果你想使用现有的控制器

 // 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]; 

这应该将您的导航栏的中心视图设置为分段控件。

希望我能帮助!

编辑:如果你需要更多的帮助,这些类的苹果文档是相当彻底的:

UINavigationItem

UINavigationBar的