我正在尝试添加 UISegmentedControl
以编程方式作为 titleView
在UINavigationController
.但它没有出现。经过进一步调查,我发现 titleView
如果 leftBarButtonItem
属性被忽略未设置为 nil
根据Apple docs .所以我将它设置为 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 应用程序。主 Controller 是UITabBarController
.单击某个选项卡时,我想显示 UITableViewController
.由于您无法在 UITableViewController
中显示导航栏,我发现我必须添加一个 UINavigationController
并实现 UITableViewController
在里面。这就是我的应用程序的基本外观,
仪表板 View Controller 连接到一个继承自 UINavigationController
的类
类(class)。也许这就是问题所在?
因为我刚刚创建了一个小的测试应用程序,所以放了一个 UIViewController
, 嵌入 UINavigationController
并将我在上面的原始问题中发布的代码写在 UIViewController
中的 ViewDidLoad 和分段控件显示得很好。现在我不知道如何在我的主应用程序中执行相同的操作,因为没有其他 View Controller 或任何连接到导航 Controller 的东西。
对不起,如果我让事情变得更糟。如果有任何不清楚的地方,请发表评论。
最佳答案
我想您必须将 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];
}
希望对您有所帮助!
关于ios - 在 UINavigationController 中添加一个 UISegmentedControl 作为 titleView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15199383/