在UINavigationController中添加UISegmentedControl作为titleView

时间:2013-03-04 10:28:06

标签: ios objective-c uinavigationcontroller uisegmentedcontrol titleview

我正在尝试以编程方式在UISegmentedControl中添加titleView作为UINavigationController。但它没有出现。经过进一步调查,我发现如果根据Apple docs titleView未设置为leftBarButtonItem,则会忽略nil属性。所以我将它设置为nil但仍然没有显示分段控件!

以下是我的代码。

- (void)viewDidLoad
{
    [super viewDidLoad];

    self.navigationItem.leftBarButtonItem = nil;
    UISegmentedControl *statFilter = [[UISegmentedControl alloc] initWithItems:[NSArray arrayWithObjects:@"Personnal", @"Department", @"Company", nil]];
    [statFilter setSegmentedControlStyle:UISegmentedControlStyleBar];
    self.navigationItem.titleView = statFilter;
}

我该怎么办?我在这里缺少什么?

感谢。

编辑

感谢所有回复。然而,他们都没有为我工作,所以我深入了解。它必须是我布置我的应用程序的方式。我可能早就应该提到了。道歉。

我正在创建的是Storyboard应用。主控制器是UITabBarController。点击某个标签后,我想显示UITableViewController。由于您无法在UITableViewController中显示导航栏,因此我发现必须添加UINavigationController并在其中实施UITableViewController。这就是我的应用程序基本上的样子,

enter image description here

该Dashboard View Controller已连接到继承自UINavigationController的类  类。也许这就是问题所在?

因为我刚刚创建了一个小型测试应用,所以将UIViewController嵌入到UINavigationController中并在UIViewController的ViewDidLoad中编写我在原始问题中发布的代码并且分段控件显示就好了。现在我不知道如何在我的主应用程序中执行相同操作,因为没有其他视图控制器或任何连接到导航控制器的内容。

对不起,如果我让事情变得更糟。如果有任何不清楚的地方请评论。

2 个答案:

答案 0 :(得分:1)

我猜你必须让UISegmentedControll成为UIBarButtonItem:

更新: 此代码使SegmentedControll居中:

- (void)viewDidLoad{
    self.title = nil;
    UISegmentedControl *statFilter = [[UISegmentedControl alloc] initWithItems:[NSArray arrayWithObjects:@"Personnal", @"Department", @"Company", nil]];
    [statFilter setSegmentedControlStyle:UISegmentedControlStyleBar];

    NSMutableArray *buttonArray     = [[NSMutableArray alloc] init];
    UIBarButtonItem *flexibleSpace  = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
    [buttonArray addObject:flexibleSpace];
    [buttonArray addObject:[[UIBarButtonItem alloc] initWithCustomView:statFilter]];
    [buttonArray addObject:flexibleSpace];

    self.navigationItem.leftBarButtonItems = buttonArray;
    [buttonArray release];
}

我希望这会帮助你!

答案 1 :(得分:0)

使用此我希望这会对您有所帮助

- (void)viewDidLoad
{
    [super viewDidLoad];
    UIView * navview = [[UIView alloc] initWithFrame:CGRectMake(10, 10, 160,80)];
    self.navigationItem.leftBarButtonItem = nil;
    UISegmentedControl *statFilter = [[UISegmentedControl alloc] initWithItems:[NSArray arrayWithObjects:@"Personnal", @"Department", @"Company", nil]];
    [statFilter setSegmentedControlStyle:UISegmentedControlStyleBar];
    [navview addsubview:statFilter];
    self.navigationItem.titleView = navview;
}