ios - 在 UINavigationController 中添加一个 UISegmentedControl 作为 titleView

标签 ios objective-c uinavigationcontroller uisegmentedcontrol titleview

我正在尝试添加 UISegmentedControl以编程方式作为 titleViewUINavigationController .但它没有出现。经过进一步调查,我发现 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在里面。这就是我的应用程序的基本外观,

enter image description here

仪表板 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/

相关文章:

iOS 跨 View Controller 共享 'global data'

ios - 在 Swift 中捕获 [weak self] 的 Realm 通知

ios - NSOperationQueue在所有操作完成之前已完成

ios - 一个 BarButtonItem 的多个操作

ios - UINavigationControllerDelegate 方法,在 ios 8 中使用导航 Controller 自定义转换

objective-c - 为什么在发送 NSFetchedResultsChangeDelete 事件的核心数据中更改记录?

iOS 13 暗模式 : UIColor. 用于 NSAttributedString 时链接太暗

ios - Swift 的 Spotify API

objective-c - 多个 View 使用的 CoreLocation 单例委托(delegate)方法