本文介绍了如何在UINavigationItem中添加UISegmentControl ..?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在 UINavigationItem 中添加 UISegmentedControl
我想用段控件创建一个 UINavigationBar ,它添加了导航栏的标题。

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

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;

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

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.

谢谢

推荐答案

你几乎就在那里,你只需要将分段控件添加到UINavigationItem中将其添加到您的UINavigationBar:

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.

希望我能提供帮助!

编辑:如果您需要更多帮助,这些课程的Apple文档非常全面:

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

这篇关于如何在UINavigationItem中添加UISegmentControl ..?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-01 22:10