如何以编程方式在iPad上的工具栏中添加UISegmentedControl

时间:2012-08-16 11:10:09

标签: ios ipad uitoolbar uisegmentedcontrol

我在iPad上的工具栏中添加UISegmentedControl有一些奇怪的问题。我用根控制器创建了一个UINavigationController,它有以下几种方法:

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];

    UINavigationController *navigationController = [self navigationController];
    navigationController.toolbar.barStyle = UIBarStyleBlackOpaque;
    navigationController.toolbarHidden = NO;
}

- (NSArray *)toolbarItems
{
    UIBarButtonItem *flexibleSpace = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:NULL];
    return [NSArray arrayWithObjects:[self segmentedControlItem], flexibleSpace, nil];
}

- (UISegmentedControl *)segmentedControl
{
    if (_segmentedControl) {
        return _segmentedControl;
    }

    NSArray *items = [NSArray arrayWithObjects:@"Segment 1", @"Segment 2", nil];
    _segmentedControl = [[UISegmentedControl alloc] initWithItems:items];
    _segmentedControl.segmentedControlStyle = UISegmentedControlStyleBar;

    return _segmentedControl;
}

- (UIBarButtonItem *)segmentedControlItem
{
    UIBarButtonItem *buttonItem = [[UIBarButtonItem alloc] initWithCustomView:self.segmentedControl];
    buttonItem.style = UIBarButtonItemStyleBordered;
    return buttonItem;
}

但是在控制器出现后,segmentedControl在工具栏上不可见。怎么解决?我已经检查过segmentedControl存在于工具栏项中,它有大小,没有隐藏,但是我看不到它。

(lldb) po [[[[[self navigationController] toolbar] items] objectAtIndex:0] customView]
(id) $3 = 0x08e39a10 <UISegmentedControl: 0x8e39a10; frame = (7 8; 300 30); opaque = NO; layer = <CALayer: 0x8e63230>>

1 个答案:

答案 0 :(得分:0)

我有一个解决方法。如果要在工具栏中添加- (NSArray *)toolbarItems,则覆盖UISegmentedControl似乎是不安全的。在控制器加载后,最好添加一些方法来配置工具栏。

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self configureToolbar];
}

- (void)configureToolbar
{
    UINavigationController *navigationController = [self navigationController];
    navigationController.toolbar.barStyle = UIBarStyleBlackOpaque;
    navigationController.toolbarHidden = NO;
    // Add toolbar items here
    UIBarButtonItem *flexibleSpace = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:NULL];
    self.toolbarItems = [NSArray arrayWithObjects:[self segmentedControlItem], flexibleSpace, nil];
}

这种方法可以让你得到结果