【问题标题】:How to add UISegmentedControl in toolbar on iPad programmatically如何以编程方式在 iPad 的工具栏中添加 UISegmentedControl
【发布时间】:2012-08-16 11:10:08
【问题描述】:

我在 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>>

【问题讨论】:

  • 好问题,但在生成视图控制器时我有很多自定义逻辑。因此,以编程方式处理它似乎更容易。
  • 一些不赞成投票的理由会很好......

标签: ios ipad uitoolbar uisegmentedcontrol


【解决方案1】:

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

- (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];
}

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-24
    • 1970-01-01
    • 2015-11-30
    • 2014-07-20
    • 1970-01-01
    相关资源
    最近更新 更多